我正在尝试下载给定网址的网页。但有时我会收到403错误(禁止)或404错误。我想处理所有这些情况并获取HTML。 即使它是404我想读取HTML内容。我试图在这里处理cookie,但如何解决各种错误代码?
URL obj = new URL(url);
HttpURLConnection c = (HttpURLConnection) obj.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = c.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(c.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
答案 0 :(得分:0)
如果您希望/需要单独响应每个可能的 responseCode ,那么在关闭InputStream后,您可以尝试以下方法:
switch(responseCode)
{
case HttpURLConnection.HTTP_FORBIDDEN:
{
someMethodToHandle403_Forbidden(response);
break;
}
case HttpURLConnection.HTTP_NOT_FOUND:
{
someMethodToHandle404_NotFound(response);
break;
}
case HttpURLConnection.HTTP_UNAVAILABLE:
{
someMethodToHandle503_Unavailable(response);
break;
}
...
*...however many additional http response code cases you're going to handle...*
...
}