HttpURLConnection 发送 JSON POST 请求到 Apache/PHP
HttpURLConnection sending JSON POST request to Apache/PHP
我正在为 HttpURLConnection 和 OutputStreamWriter 苦苦挣扎。
代码确实到达了服务器,因为我收到了一个有效错误
回复。发出了 POST 请求,但没有收到数据
服务器端。
非常感谢任何有关正确使用此东西的提示。
代码在 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;
}
我要发送的JSON:
JSONObject request = {
"action":"login",
"user":"mogens",
"auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7",
"location":{
"accuracy":25,
"provider":"network",
"longitude":120.254944,
"latitude":14.847808
}
};
我从服务器得到的响应:
JSONObject response = {
"success":false,
"response":"Unknown or Missing action.",
"request":null
};
我应该得到的回应:
JSONObject response = {
"success":true,
"response":"Welcome Mogens Burapa",
"request":"login"
};
服务器端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;
?>
并且 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}
如果我将 ?action=login
附加到 URL
,我可以从服务器获得成功响应。但只有 action 参数注册服务器端。
{"success":true,"message":"Welcome ","request":"login"}
结论一定是URLConnection.write(output.getBytes("UTF-8"));
没有传输任何数据
好吧,数据终于传输过来了。
@greenaps 提供的解决方案可以解决问题:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
PHP 上面的脚本已更新以显示解决方案。
尝试使用 DataOutputStream 而不是 OutputStreamWriter。
DataOutputStream out = new DataOutputStream(_conn.getOutputStream());
out.writeBytes(your json serialized string);
out.close();
echo (file_get_contents('php://input'));
将显示 json 文本。像这样使用它:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
我让服务器告诉我它从我那里得到了什么。
请求Headers和POSTBody
<?php
$requestHeaders = apache_request_headers();
print_r($requestHeaders);
print_r("\n -= POST Body =- \n");
echo file_get_contents( 'php://input' );
?>
很有魅力)
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.
遇到同样的情况,来@greenapps 回答。
您应该知道从 'post request'
收到的服务器
我首先在服务器端做什么:
echo (file_get_contents('php://input'));
然后print/Toast/show客户端消息响应。确保其格式正确,例如:
{"username": "yourusername", "password" : "yourpassword"}
如果这样的响应(因为你 post 请求 yourHashMap.toString()
):
{username=yourusername,password=yourpassword}
改用.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() + "}";
}
我正在为 HttpURLConnection 和 OutputStreamWriter 苦苦挣扎。
代码确实到达了服务器,因为我收到了一个有效错误 回复。发出了 POST 请求,但没有收到数据 服务器端。
非常感谢任何有关正确使用此东西的提示。
代码在 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;
}
我要发送的JSON:
JSONObject request = {
"action":"login",
"user":"mogens",
"auth":"b96f704fbe702f5b11a31524bfe5f136efea8bf7",
"location":{
"accuracy":25,
"provider":"network",
"longitude":120.254944,
"latitude":14.847808
}
};
我从服务器得到的响应:
JSONObject response = {
"success":false,
"response":"Unknown or Missing action.",
"request":null
};
我应该得到的回应:
JSONObject response = {
"success":true,
"response":"Welcome Mogens Burapa",
"request":"login"
};
服务器端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;
?>
并且 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}
如果我将 ?action=login
附加到 URL
,我可以从服务器获得成功响应。但只有 action 参数注册服务器端。
{"success":true,"message":"Welcome ","request":"login"}
结论一定是URLConnection.write(output.getBytes("UTF-8"));
好吧,数据终于传输过来了。
@greenaps 提供的解决方案可以解决问题:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
PHP 上面的脚本已更新以显示解决方案。
尝试使用 DataOutputStream 而不是 OutputStreamWriter。
DataOutputStream out = new DataOutputStream(_conn.getOutputStream());
out.writeBytes(your json serialized string);
out.close();
echo (file_get_contents('php://input'));
将显示 json 文本。像这样使用它:
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
我让服务器告诉我它从我那里得到了什么。
请求Headers和POSTBody
<?php
$requestHeaders = apache_request_headers();
print_r($requestHeaders);
print_r("\n -= POST Body =- \n");
echo file_get_contents( 'php://input' );
?>
很有魅力)
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.
遇到同样的情况,来@greenapps 回答。 您应该知道从 'post request'
收到的服务器我首先在服务器端做什么:
echo (file_get_contents('php://input'));
然后print/Toast/show客户端消息响应。确保其格式正确,例如:
{"username": "yourusername", "password" : "yourpassword"}
如果这样的响应(因为你 post 请求 yourHashMap.toString()
):
{username=yourusername,password=yourpassword}
改用.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() + "}";
}