我正在尝试实现一个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();
}
}
但是我最终需要获取响应。我尝试实例化这个类,然后将响应作为成员获取,但是那样并没有奏效。 有什么建议吗?