我对 PHP、JavaScript 和许多其他脚本语言有经验,但对 Java 或 Android 没有太多经验。
我正在寻找一种将 POST 数据发送到 PHP 脚本并显示结果的方法。
原文由 OMGKurtNilsen 发布,翻译遵循 CC BY-SA 4.0 许可协议
我对 PHP、JavaScript 和许多其他脚本语言有经验,但对 Java 或 Android 没有太多经验。
我正在寻找一种将 POST 数据发送到 PHP 脚本并显示结果的方法。
原文由 OMGKurtNilsen 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于 Android = > 5
org.apache.http 类和 AndroidHttpClient 类已在 Android 5.1 中 弃用。这些类不再维护,您应该尽快将使用这些 API 的任何应用程序代码迁移到 URLConnection 类。
https://developer.android.com/about/versions/android-5.1.html#http
想使用 HttpUrlConnection 共享我的代码
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
…
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
你也可以 发布 方法:
conn.setRequestMethod("POST");
更新 21/02/2016
对于 json 的 发布 请求,请参见以下示例:
public class Empty extends
AsyncTask<Void, Void, Boolean> {
String urlString = "http://www.yoursite.com/";
private final String TAG = "post json example";
private Context context;
private int advertisementId;
public Empty(Context contex, int advertisementId) {
this.context = contex;
this.advertisementId = advertisementId;
}
@Override
protected void onPreExecute() {
Log.e(TAG, "1 - RequestVoteTask is about to start...");
}
@Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
String response = "";
Log.e(TAG, "2 - pre Request to response...");
try {
response = performPostCall(urlString, new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put("Accept", "application/json");
put("Content-Type", "application/json");
}
});
Log.e(TAG, "3 - give Response...");
Log.e(TAG, "4 " + response.toString());
} catch (Exception e) {
// displayLoding(false);
Log.e(TAG, "Error ...");
}
Log.e(TAG, "5 - after Response...");
if (!response.equalsIgnoreCase("")) {
try {
Log.e(TAG, "6 - response !empty...");
//
JSONObject jRoot = new JSONObject(response);
JSONObject d = jRoot.getJSONObject("d");
int ResultType = d.getInt("ResultType");
Log.e("ResultType", ResultType + "");
if (ResultType == 1) {
status = true;
}
} catch (JSONException e) {
// displayLoding(false);
// e.printStackTrace();
Log.e(TAG, "Error " + e.getMessage());
} finally {
}
} else {
Log.e(TAG, "6 - response is empty...");
status = false;
}
return status;
}
@Override
protected void onPostExecute(Boolean result) {
//
Log.e(TAG, "7 - onPostExecute ...");
if (result) {
Log.e(TAG, "8 - Update UI ...");
// setUpdateUI(adv);
} else {
Log.e(TAG, "8 - Finish ...");
// displayLoding(false);
// finish();
}
}
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(context.getResources().getInteger(
R.integer.maximum_timeout_to_server));
conn.setConnectTimeout(context.getResources().getInteger(
R.integer.maximum_timeout_to_server));
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
Log.e(TAG, "11 - url : " + requestURL);
/*
* JSON
*/
JSONObject root = new JSONObject();
//
String token = Static.getPrefsToken(context);
root.put("securityInfo", Static.getSecurityInfo(context));
root.put("advertisementId", advertisementId);
Log.e(TAG, "12 - root : " + root.toString());
String str = root.toString();
byte[] outputBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputBytes);
int responseCode = conn.getResponseCode();
Log.e(TAG, "13 - responseCode : " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.e(TAG, "14 - HTTP_OK");
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
Log.e(TAG, "14 - False - HTTP_OK");
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
更新 24/08/2016
使用一些最好的库,例如:
因为 :
在较低的 API 级别(主要是在 Gingerbread 和 Froyo 上),HttpUrlConnection 和 HttpClient 远非完美
自从引入 Honeycomb (API 11) 以来,必须在不同于主线程的单独线程上执行网络操作
原文由 Adnan Abdollah Zaki 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答1.8k 阅读✓ 已解决
2 回答2.2k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
注意(2020 年 10 月):以下答案中使用的 AsyncTask 在 Android API 级别 30 中已弃用。请参阅 官方文档 或 此博客文章 以获取更多更新示例
更新(2017 年 6 月)适用于 Android 6.0+ 的答案。感谢 @Rohit Suthar 、 @Tamis Bolvari 和 @sudhiskr 的评论。
参考:
原始答案(2010 年 5 月)
注意:此解决方案已过时。它仅适用于最高 5.1 的 Android 设备。 Android 6.0 及更高版本不包括此答案中使用的 Apache http 客户端。
来自 Apache Commons 的 Http Client 是必经之路。它已经包含在android中。这是一个如何使用它进行 HTTP Post 的简单示例。