我想要做的就是使用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