java HttpURLConnection 向 Apache/PHP 发送 JSON POST 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29680237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpURLConnection sending JSON POST request to Apache/PHP
提问by Mogens TrasherDK
I'm struggling with HttpURLConnection and OutputStreamWriter.
我正在为 HttpURLConnection 和 OutputStreamWriter 苦苦挣扎。
The code actually reaches the server, as I do get a valid error response back. A POST request is made, but no data is received server-side.
代码实际上到达了服务器,因为我确实得到了一个有效的错误响应。发出 POST 请求,但服务器端未收到任何数据。
Any hints to proper usage of this thingy is highly appreciated.
任何有关正确使用这个东西的提示都非常感谢。
The code is in an AsyncTask
代码在 AsyncTask 中
protected JSONObject doInBackground(Void... params) {
try {
url = new URL(destination);
client = (HttpURLConnection) url.openConnection();
client.setDoOutput(true);
client.setDoInput(true);
client.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
client.setRequestMethod("POST");
//client.setFixedLengthStreamingMode(request.toString().getBytes("UTF-8").length);
client.connect();
Log.d("doInBackground(Request)", request.toString());
OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
String output = request.toString();
writer.write(output);
writer.flush();
writer.close();
InputStream input = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("doInBackground(Resp)", result.toString());
response = new JSONObject(result.toString());
} catch (JSONException e){
this.e = e;
} catch (IOException e) {
this.e = e;
} finally {
client.disconnect();
}
return response;
}
The JSON I'm trying to send:
我试图发送的 JSON:
JSONObject request = {
"action":"login",
"user":"mogens",
"auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7",
"location":{
"accuracy":25,
"provider":"network",
"longitude":120.254944,
"latitude":14.847808
}
};
And the response I get from the server:
我从服务器得到的响应:
JSONObject response = {
"success":false,
"response":"Unknown or Missing action.",
"request":null
};
And the response I should have had:
我应该得到的回应是:
JSONObject response = {
"success":true,
"response":"Welcome Mogens Burapa",
"request":"login"
};
The server-side PHP script:
服务器端 PHP 脚本:
<?php
$json = file_get_contents('php://input');
$request = json_decode($json, true);
error_log("JSON: $json");
error_log('DEBUG request.php: ' . implode(', ',$request));
error_log("============ JSON Array ===============");
foreach ($request as $key => $val) {
error_log("$key => $val");
}
switch($request['action'])
{
case "register":
break;
case "login":
$response = array(
'success' => true,
'message' => 'Welcome ' . $request['user'],
'request' => $request['action']
);
break;
case "location":
break;
case "nearby":
break;
default:
$response = array(
'success' => false,
'response' => 'Unknown or Missing action.',
'request' => $request['action']
);
break;
}
echo json_encode($response);
exit;
?>
And the logcat output in Android Studio:
Android Studio 中的 logcat 输出:
D/doInBackground(Request)﹕ {"action":"login","location":{"accuracy":25,"provider":"network","longitude":120.254944,"latitude":14.847808},"user":"mogens","auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7"}
D/doInBackground(Resp)﹕ {"success":false,"response":"Unknown or Missing action.","request":null}
If I append ?action=login
to the URL
I can get a success response from the server. But only the actionparameter registers server-side.
如果我附加?action=login
到URL
我可以从服务器获得成功响应。但只有action参数注册服务器端。
{"success":true,"message":"Welcome ","request":"login"}
{"success":true,"message":"Welcome ","request":"login"}
The conclusion must be that no data is transferred by URLConnection.write(output.getBytes("UTF-8"));
结论必须是没有数据被传输 URLConnection.write(output.getBytes("UTF-8"));
Well, data get transferred after all.
好吧,毕竟数据会被传输。
Solution offered by @greenaps does the trick:
@greenaps 提供的解决方案可以解决问题:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
PHP script above updated to show the solution.
上面的 PHP 脚本已更新以显示解决方案。
采纳答案by greenapps
echo (file_get_contents('php://input'));
Will show you the json text. Work with it like:
将向您显示 json 文本。像这样使用它:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
回答by Inoy
I've made server tell me what it got from me.
我让服务器告诉我它从我这里得到了什么。
Request Headers and POST Body
请求头和 POST 正文
<?php
$requestHeaders = apache_request_headers();
print_r($requestHeaders);
print_r("\n -= POST Body =- \n");
echo file_get_contents( 'php://input' );
?>
Works like a charm)
奇迹般有效)
回答by Sri777
try to use DataOutputStream instead of OutputStreamWriter.
尝试使用 DataOutputStream 而不是 OutputStreamWriter。
DataOutputStream out = new DataOutputStream(_conn.getOutputStream());
out.writeBytes(your json serialized string);
out.close();
回答by Muchtarpr
The code actually reaches the server, as I do get a valid error response back. A POST request is made, but no data is received server-side.
代码实际上到达了服务器,因为我确实得到了一个有效的错误响应。发出 POST 请求,但服务器端未收到任何数据。
got this same situation, and come to @greenapps answer. you should know what server recieved from 'post request'
遇到了同样的情况,然后来@greenapps 回答。您应该知道从“发布请求”中收到的服务器
what i do first on the server side :
我首先在服务器端做什么:
echo (file_get_contents('php://input'));
then print/Toast/show message response on the client side. make sure its correct form, like :
然后在客户端打印/吐司/显示消息响应。确保其正确的形式,如:
{"username": "yourusername", "password" : "yourpassword"}
if the response like this (because you post the request with yourHashMap.toString()
) :
如果响应是这样的(因为你用 发布了请求yourHashMap.toString()
):
{username=yourusername,password=yourpassword}
instead using .toString(), use this method instead to turn HashMap into String :
而不是使用 .toString(),而是使用此方法将 HashMap 转换为 String :
private String getPostDataString(HashMap<String, String> postDataParams) {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String,String> entry : postDataParams.entrySet()){
if(first){
first = false;
}else{
result.append(",");
}
result.append("\"");
result.append(entry.getKey());
result.append("\":\"");
result.append(entry.getValue());
result.append("\"");
}
return "{" + result.toString() + "}";
}