gpt4 book ai didi

java - 如何使用异步和 onPostExecute 向 PHP 发送值并获取响应

转载 作者:行者123 更新时间:2023-12-02 04:55:50 25 4
gpt4 key购买 nike

如何使用 异步HttpRequest 将值发送到 php 页面并获取响应,然后使用 OnPostExcute 对其执行某些操作。

Java:

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}

protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
// Do something with the response here
// ....
}

public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
}

}

PHP:

<?php
// return the value back to the app
echo $_POST["myHttpData"];

?>

最佳答案

private class MyAsyncTask extends AsyncTask<String, HttpResponse, HttpResponse>{

@Override
protected HttpResponse doInBackground(String... params) {
// TODO Auto-generated method stub
return postData(params[0]);
}

protected void onPostExecute(HttpResponse result){
View pb;
pb.setVisibility(View.GONE);

HttpEntity entity = result.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
Toast.makeText(mContext, responseString, Toast.LENGTH_LONG).show();
}

@SuppressWarnings("unchecked")
public HttpResponse postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("__url_to_file.php");

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
return response;
}

}

你可以用上面的方法做一些事情。这肯定会将 HttpResponse 传递给 onPostExecute 方法,并允许您用它做一些事情。

不过,我会看一下这一行:

httppost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs));

因为我觉得这不太合适。我必须添加强制转换才能让编译器满意。这可能不是所需的结果(但重点是让 ASyncTask 允许处理 HttpResponse)。

关于java - 如何使用异步和 onPostExecute 向 PHP 发送值并获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28782199/

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