我正在尝试实现一个 httpClient 类,它是一个 AsyncTask (否则由于我的主线程中有一个连接,我会得到一个异常)。我试过这样的事情:
private class execHttpAsync extends AsyncTask <String, String, HttpResponse>
{
public String resultString;
@Override
protected HttpResponse doInBackground(String... params)
{
String url = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Content-Type", "text/xml");
HttpResponse response;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(HttpResponse result)
{
StringBuffer returned = new StringBuffer();
InputStream content = result.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(content, "UTF-8"));
String line;
while ((line = rd.readLine()) != null)
{
String endOfLine = "";
returned.append(line + endOfLine);
}
content.close();
String retVal = returned.toString();
try
{
String header = retVal.substring(0, 1);
if (!header.equals("<"))
{
retVal = retVal.replace(header, "");
}
}
catch (Exception e)
{
// TODO: handle exception
}
resultString = returned.toString();
}
}
但我最终需要得到回应。我试图实例化这个类,然后作为成员获得响应,但没有成功。有什么建议么 ?