我想要做的就是使用AsyncTask来做一个http请求。这是我的代码到目前为止,但我不知道如何从我的主要活动调用这个类,以及如何获得结果。我有一个String var“uri”,它完成了我的http请求的url,我必须传递给我的类。在调用这个类之后,下一步是将结果(作为字符串)传递给一个新函数。如何传递参数并从AsyncTask Class中获取结果?
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet("http://www.mywebsite.com/xml_data/" + uri + "_meeting_info.xml?id=cacheSTOP3"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} 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) {
onPostExecute(result);
//Do anything with response..
}
}
主要活动:
RequestTask getXML = new RequestTask();
getXML.execute(MyVarString);
//Now send the results from above to a new function
Document doc = XMLfunctions.XMLfromString(getdata);
有没有原因为什么这个问题被拒绝投票?请解释一下,以便我确保将来更加清晰。 – Denoteone
** super.onPostExecute(result); **不需要调用。 – NOSTRA
我没有投票,但我会猜测它是因为a)AsyncTasks很常见,有一点研究,你可以找到你的答案或b)已经有一个常见的问题,你可以搜索找到你的回答。我个人不介意,但有些人对这些东西感到敏感 – Joe