最近在学习网络加载库 async-http-client 有两个问题存在疑惑,恳请有研究过的 V 友指点一下:
-
SyncHttpClient 为何要在子线程中使用?
我已经知道 AsyncHttpClient 发异步请求是在
sendRequest方法中,通过以下代码新建AsyncHttpRequest提交到线程池。AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request);而 SyncHttpClient 是继承自 AsyncHttpClient ,重写了
sendRequest,但是在其方法中也调用了:newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run();我的疑惑:这里
newAsyncHttpRequest返回的AsyncHttpRequest同样实现了Runnable并调用了run()方法,那么这不也是在子线程执行网络操作了。为什么我直接在 UI 线程调用SyncHttpClient client = new SyncHttpClient(); client.get(MainActivity.this, "http://www.baidu.com", new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } });为什么这里会报错:在主线程中执行了网络操作?
-
SyncHttpClient 是在如何在线程中进行阻塞的?
在一个子线程中进行两个请求,打印日志显示会等第一个请求结果返回才进行第二个请求,但是我查看其源码只找到一个
responseHandler.setUseSynchronousMode(true);貌似有关系,但是具体是怎么进行阻塞的还不明白?
上面是我的两个疑惑,希望请各位大神指点一下,谢谢!