【发布时间】:2015-07-07 17:41:47
【问题描述】:
我正在使用 AsyncTask 在 android 上执行 HTTP GET。它会导致将我的数据发送到 URL 的时间很长。有没有办法解决这个问题或其他可以使用的方法?
这是我的代码: 类 RequestTask 扩展 AsyncTask{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
HttpParams httpParameters = httpclient.getParams();
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
这是电话:
new RequestTask().execute("http://10.10.10.211:9081/?modelname=model1&sourcedata=" + values[1]);
【问题讨论】:
-
causes a long delay定义它,并解释 a/ 你如何观察它和 b/ 是什么让你认为它与使用异步任务有关 -
您的任务是否可能实际上并没有异步运行?尝试通过 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) 在执行器上运行它;您甚至可能想要实现类似 stackoverflow.com/a/12160159/1426565 的东西来帮助您完成想要独立运行的其他任务
-
长时间延迟是指使用我的安卓设备时需要 9-10 秒才能得到响应。当我使用 java 应用程序在我的计算机上运行相同的请求时,响应几乎是即时的。
标签: android android-asynctask http-get