Rangtian Yu Rangtian Yu - 4 months ago 18
PHP Question

Sending json to server using HttpURLConnection, data becomes key rather than value

In my app, I tried to send

JSON
data using
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();


And this is how the
JSON
string looks like:

{"name":"The Dark Knight","rating":"9"}


But when I received from the server, it becomes the key of an Array element whose value is null.

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


I'm new to
PHP
and
Slim
, my
Php
code looks like:

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

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


Why the data I write to server becomes key rather than value? I fetched out the data from key in this way:

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


But I still feel myself fucked because I'm reading from the key rather than value. Is there any misunderstanding or mistake leads me to this weird situation? Thank you.

Answer

As mentioned by @geggleto:

if it's not being parsed in getParsedBody then the content-type is wrong in your request.


You can fix it by sending the correct header:

httpConnection.setRequestProperty("Content-Type","application/json");
Comments