我想实现一个类,它将处理我的申请,所有的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