(为清楚起见进行了更新)我可能需要根据返回的结果在 Android AsyncTask 中重新运行 HTTP 请求。我在下面粘贴了一个异步任务的简单示例。我不会取回错误代码,而是取回一个临时工作 ID,告诉我服务器正在处理我的请求。我需要每隔几秒钟检查一次并向服务器发送工作 ID,直到它完成并给我我的数据。就是这样!听起来很简单,但我似乎无法弄清楚:
private class HttpGetter extends AsyncTask<URL, Void, Void> {
@Override
protected Void doInBackground(URL... urls) {
// TODO Auto-generated method stub
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urls[0]);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.v("Getter", "Your data: " + builder.toString()); // response
// data
} else {
Log.e("Getter", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
然后使用 AsyncTask:
HttpGetter get = new HttpGetter();
get.execute("http://www.google.es");