我在尝试从字符串中获取HTTP响应的主体时遇到了困难。所以根据我的代码,我应该从名为“responseString”的字符串中的PHP页面得到响应,但是因为这是在ASynchTask中,我无法在其他任何地方访问该字符串,所以如何才能收到字符串?
例如,我想将此字符串拍摄到文本视图中以进行测试,我该怎么做?我是否错误地阅读了代码?我的反应是不是被放进那个字符串了?
这是我的代码:
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 );
答案 0 :(得分:1)
执行doInBackground
之后,onPostExecute
将直接启动,并且您可以在那里更新UI,因为您要返回responseString,然后在onPostExecute
中将其放入TextView
doInBackgound
的回复是onPostExecute
的忠诚,因此字符串result
是您的responseString
。
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tv.setText(result);
}
答案 1 :(得分:0)
我认为你的问题还没有解决。所以,
对于Log或Toast使用以下代码:
class RequestTask extends AsyncTask<String, String, String>{
String responseString = "";
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
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);
Log.d("Result is", responseString );
Toast.makeText(YourClass.this , responseString , Toast.LENGTH_SHORT).show();
}
}