我想用java获取url的文本。
public static String getResponseFromUrlDesktop(String url) {
try {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
问题是,当我转到一个URL并且它给了我 java.io.IOException:服务器返回HTTP响应代码:URL为
如果我打开broswer中的网址,我会收到一条文字。 无论响应代码如何,我如何始终获取GET请求的文本?
答案 0 :(得分:2)
试试这个:
public static String getResponseFromUrlDesktop(String url) {
HttpURLConnection connection = null;
StringBuilder response = new StringBuilder();
BufferedReader in = null;
try {
URL website = new URL(url);
connection = (HttpURLConnection) website.openConnection();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
} catch (IOException e) {
try {
if (connection.getResponseCode() >= 400) {
in = new BufferedReader(new InputStreamReader(
connection.getErrorStream()));
// ^^^^^^^^^^^^^^
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
return response.toString();
}
答案 1 :(得分:0)
使用BufferedReader
阅读并StringBuilder
构建必需的字符串..
protected String Method_Name(String... url){
String urls = url[0];
String texts = "";
try{
in = new java.net.URL(urls).openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
texts = sb.toString();
}catch (IOException e) {
e.printStackTrace();
}
return texts;
}