使用 HttpURLConnection 将 json 发送到服务器,数据成为键而不是值
Sending json to server using HttpURLConnection, data becomes key rather than value
在我的应用程序中,我尝试使用 HttpUrlConnection
:
发送 JSON
数据
URL url = new URL(urlString);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setChunkedStreamingMode(0);
OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
// This write the data to server
Log.d("MyDebugMsg", json.toString());
out.write(json.toString());
out.flush();
out.close();
这就是 JSON
字符串的样子:
{"name":"The Dark Knight","rating":"9"}
但是当我从服务器接收到时,它变成了一个值为空的数组元素的键。
Array
(
[{"name":"The_Dark_Knight","rating":"9"}] =>
)
我是 PHP
和 Slim
的新手,我的 Php
代码如下:
$app->post(
'/add',
function($request, $response, $args) {
// $data = $request->getParsedBody();
// addMovieToDB($data);
$json = $request->getParsedBody();
print_r($json);
}
);
为什么我写到服务器的数据变成键而不是值?我是这样从key中取出数据的:
$array = $request->getParsedBody();
$data = json_decode(key($array));
但我仍然觉得我错了,因为我是从键而不是值读取的。是否有任何误解或错误导致我出现这种奇怪的情况?谢谢。
如@geggleto所述:
if it's not being parsed in getParsedBody then the content-type is
wrong in your request.
您可以通过发送正确的 header:
修复
httpConnection.setRequestProperty("Content-Type","application/json");
在我的应用程序中,我尝试使用 HttpUrlConnection
:
JSON
数据
URL url = new URL(urlString);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setChunkedStreamingMode(0);
OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
// This write the data to server
Log.d("MyDebugMsg", json.toString());
out.write(json.toString());
out.flush();
out.close();
这就是 JSON
字符串的样子:
{"name":"The Dark Knight","rating":"9"}
但是当我从服务器接收到时,它变成了一个值为空的数组元素的键。
Array
(
[{"name":"The_Dark_Knight","rating":"9"}] =>
)
我是 PHP
和 Slim
的新手,我的 Php
代码如下:
$app->post(
'/add',
function($request, $response, $args) {
// $data = $request->getParsedBody();
// addMovieToDB($data);
$json = $request->getParsedBody();
print_r($json);
}
);
为什么我写到服务器的数据变成键而不是值?我是这样从key中取出数据的:
$array = $request->getParsedBody();
$data = json_decode(key($array));
但我仍然觉得我错了,因为我是从键而不是值读取的。是否有任何误解或错误导致我出现这种奇怪的情况?谢谢。
如@geggleto所述:
if it's not being parsed in getParsedBody then the content-type is wrong in your request.
您可以通过发送正确的 header:
修复httpConnection.setRequestProperty("Content-Type","application/json");