使用HttpURLConnection将json发送到服务器,数据变为关键而不是值

问题描述 投票:-1回答:1

在我的应用程序中,我尝试使用JSON发送HttpUrlConnection数据:

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"}

但是当我从服务器收到它时,它成为一个值为null的Array元素的键。

Array
(
[{"name":"The_Dark_Knight","rating":"9"}] => 
)

我是PHPSlim的新手,我的Php代码如下:

$app->post(
    '/add',
    function($request, $response, $args) {
        // $data = $request->getParsedBody();
        // addMovieToDB($data);

        $json = $request->getParsedBody();
        print_r($json);
    }
);

为什么我写入服务器的数据变成关键而不是价值?我以这种方式从密钥中取出数据:

$array = $request->getParsedBody();
$data = json_decode(key($array));

但我仍然觉得我错了,因为我是从关键而非价值中读取的。是否有任何误解或错误导致我这种奇怪的情况?谢谢。

php android slim
1个回答
1
投票

如@geggleto所述:

如果它没有在getParsedBody中解析,那么请求中的内容类型是错误的。


您可以通过发送正确的标头来修复它:

httpConnection.setRequestProperty("Content-Type","application/json");
© www.soinside.com 2019 - 2024. All rights reserved.