我需要在给定的网站中找到损坏的链接并显示它们的状态代码。我可以检查网站是否失败,因为抛出异常。但我无法获得状态码。我已经检查了这些建议: httpclient.execute(httpget) 之后的 Android 代码没有在 try (using AsyncTask) HttpClient get status code中运行
我运行异步任务。
这是我的 AsyncTask 变量:
private class WebPageDownloadTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
int statusCode;
HttpResponse execute;
这是我的doInBackground:
@Override
protected String doInBackground(String... urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
String response = "";
try {
execute = client.execute(httpGet);
statusCode = execute.getStatusLine().getStatusCode();
Log.d("test", statusCode + "");
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (HttpResponseException e) {
e.printStackTrace();
statusCode = execute.getStatusLine().getStatusCode();
Log.d("test", statusCode + "");
} catch (IOException e) {
e.printStackTrace();
statusCode = execute.getStatusLine().getStatusCode();
Log.d("test", statusCode + "");
}
return response;
}
如果我提供错误的互联网地址,execute.getStatusLine().getStatusCode() 会抛出 nullPointerException。