gpt4 book ai didi

java - 如何使用 AsyncTask 读取 HTTP 响应?

转载 作者:行者123 更新时间:2023-11-30 03:11:49 24 4
gpt4 key购买 nike

我在尝试从字符串中获取 HTTP 响应的主体时遇到困难。因此,根据我的代码,我应该在名为“responseString”的字符串中收到来自 PHP 页面的响应,但是因为这是在 ASynchTask 中,所以我无法在其他任何地方访问该字符串,那么我如何接收该字符串?

例如,出于测试目的,我想将此字符串放入 TextView 中,我该怎么做?我是否错误地阅读了代码?我得到的响应没有放入该字符串中吗?

这是我的代码:

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 );

最佳答案

执行 doInBackground 之后onPostExecute将直接启动,您可以在那里更新 UI,因为您要返回 responseString,然后在 onPostExecute 中把它放在一个 TextView 中

返回doInBackgoundonPostExecute 的参数所以字符串 result是你的 responseString .

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

tv.setText(result);

}

关于java - 如何使用 AsyncTask 读取 HTTP 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com