Android ASyncTask 错误结果
Android ASyncTask wrong result
我正在尝试向服务器发出 GET 请求并 return 响应。这是我的代码。
@Override
protected String doInBackground(String... params) {
String url = getBaseUrl() + params[0] + "?" + params[1] + "=" + params[2];
String response = "";
try {
HttpClient client = new DefaultHttpClient();
String getURL = url;
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// do something with the response
response = EntityUtils.toString(resEntityGet);
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
当调试响应具有正确的值但当我调用该方法时,响应变成了其他东西。我这样称呼它:
HTTPConnector connector = new HTTPConnector("http://www.thetvdb.com/api/");
try {
AsyncTask<String, Void, String> result = connector.execute("GetSeries.php", "seriesname", "Arrow");
String result2 = result.toString();
System.out.println(result2);
} catch (Exception e) {
e.printStackTrace();
}
此处的结果与 doInBackground 方法中的响应不同。这怎么可能,我该如何解决?
你错误地使用了AsyncTask。您应该在其 onPostExecute() 方法中获得响应字符串,代码如下:
@Override
protected void onPostExecute(String result) {
// The result is the response String you want.
}
见文档 AsyncTask.execute 任务 return 本身 (this) 以便调用者可以保留对它的引用 我们将使用它来检查AsyncTask
的状态就像任务是 运行、待处理或完成,而不是 doInBackground
的 return 结果。
onPostExecute
方法在 doInBackground
方法执行完成以将结果传递给 UI 线程时被调用:
@Override
protected void onPostExecute(String result) {
// update UI here
}
我正在尝试向服务器发出 GET 请求并 return 响应。这是我的代码。
@Override
protected String doInBackground(String... params) {
String url = getBaseUrl() + params[0] + "?" + params[1] + "=" + params[2];
String response = "";
try {
HttpClient client = new DefaultHttpClient();
String getURL = url;
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// do something with the response
response = EntityUtils.toString(resEntityGet);
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
当调试响应具有正确的值但当我调用该方法时,响应变成了其他东西。我这样称呼它:
HTTPConnector connector = new HTTPConnector("http://www.thetvdb.com/api/");
try {
AsyncTask<String, Void, String> result = connector.execute("GetSeries.php", "seriesname", "Arrow");
String result2 = result.toString();
System.out.println(result2);
} catch (Exception e) {
e.printStackTrace();
}
此处的结果与 doInBackground 方法中的响应不同。这怎么可能,我该如何解决?
你错误地使用了AsyncTask。您应该在其 onPostExecute() 方法中获得响应字符串,代码如下:
@Override
protected void onPostExecute(String result) {
// The result is the response String you want.
}
见文档 AsyncTask.execute 任务 return 本身 (this) 以便调用者可以保留对它的引用 我们将使用它来检查AsyncTask
的状态就像任务是 运行、待处理或完成,而不是 doInBackground
的 return 结果。
onPostExecute
方法在 doInBackground
方法执行完成以将结果传递给 UI 线程时被调用:
@Override
protected void onPostExecute(String result) {
// update UI here
}