我想實現一個類,它將處理我的申請,所有的HTTP請求,這將是基本上是:Android的HTTP請求的AsyncTask
- 獲取業務(GET)的列表;
- 執行登錄(POST);
- 更新位置(POST)。
所以,我將不得不從服務器(JSON)得到結果字符串,並將其傳遞給另一個方法來處理響應。
我現在有這樣的方法:
public class Get extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... arg) {
String linha = "";
String retorno = "";
mDialog = ProgressDialog.show(mContext, "Aguarde", "Carregando...", true);
// Cria o cliente de conexão
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(mUrl);
try {
// Faz a solicitação HTTP
HttpResponse response = client.execute(get);
// Pega o status da solicitação
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Ok
// Pega o retorno
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// Lê o buffer e coloca na variável
while ((linha = rd.readLine()) != null) {
retorno += linha;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return retorno;
}
@Override
protected void onPostExecute(String result) {
mDialog.dismiss();
}
}
public JSONObject getJSON(String url) throws InterruptedException, ExecutionException {
// Determina a URL
setUrl(url);
// Executa o GET
Get g = new Get();
// Retorna o jSON
return createJSONObj(g.get());
}
但g.get()
返回一個空的響應。我該如何解決這個問題?
添加日誌語句將doInBackground用來記錄字符串returno的get後就一直完成以確保消息正在返回。 – 2012-01-12 01:57:04