该声明,response = httpClient.execute(httpGet, localContext);
被 try/catch 块正确包装,但如果抛出异常(例如服务器无法访问、URL 不正确或网络中断的情况),则 catch 块仅打印异常并继续。这意味着后面的语句:
reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
会遇到空指针异常,因为response
一片空白。 httpClient.execute 语句的 catch 块应该只是return
打印出错误异常后。更好的方法是只使用一组 try catch 块来解析请求和响应。像下面这样:
HttpResponse response = null;
try {
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet, localContext);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException ioex) {
Log.d(TAG, "IOException", ioex);
} catch (IllegalStateException ise) {
Log.d(TAG, "IllegalStateException", ise);
}
由于日志语句可以打印带有消息的异常,因此我刚刚为您组合了它。您不需要多余的 printStateTrace 语句。由于ClientProtocolException继承自IOException,因此您只需捕获基类即可。
另外,您可以通过在类中声明“TAG”变量来使日志语句更具可过滤性,如下所示:
public static final String TAG = VotiFragment.class.getSimpleName();
现在我已经清理完你的代码了,我刚刚意识到你遇到了另一个问题。 asynctask 的重点是避免在主线程上执行网络 I/O。但是 asynctask 所做的只是启动 HTTP 请求,但实际上并不解析响应。它只是创建阅读器对象,我认为您实际上是从 UI 线程上进行流式传输的。这意味着主线程上的剩余网络 I/O 除非响应已完全缓冲。我建议您在后台任务中进行所有解析。