我正在尝试实现一个AsClip的httpClient类(否则由于在我的主线程中有连接而得到异常)。 我试过这样的事情:
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();
}
}
但我最终需要得到回应。我试图实例化这个类,然后作为成员获得响应,但没有成功。 有什么建议吗?
答案 0 :(得分:12)
试试这种方式
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
答案 1 :(得分:1)
这是异步操作,因此类似于:
myRetValue = new myAsyncTask.execute();
不会将onPostExecute()
的返回值分配给myRetValue。你的
resultString = returned.toString();
应该导致生成returned.toString()
分配给resultString
变量的任何内容(我猜是在AsyncTask类之外声明,所以基本上你的代码看起来很乍看。你可能根本就没有任何东西returned
。尝试在AsyncTask代码中植入一些断点,并检查它是否真的像你想象的那样。