我在尝试从字符串中获取 HTTP 响应的正文时遇到了困难。所以根据我的代码,我应该在名为“responseString”的字符串中获得来自 PHP 页面的响应,但是因为这是在一个异步任务中,我无法在其他任何地方访问该字符串,那么我该如何接收该字符串?
例如,我想将此字符串拍摄到文本视图中以进行测试,我该怎么做?我是否错误地阅读了代码?我得到的响应是否没有被放入该字符串中?
这是我的代码:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
我正在使用以下内容执行:
new RequestTask().execute("http://www.mywebsite.com/android/registercheck.php?first=" + first2 + "&last=" + last2 + "&dispname=" + display2 + "&email=" + email2 + "&password=" + password2 );