Home » Java » JSON POST Data via HttpURLConnection

JSON POST Data via HttpURLConnection

Posted by: admin October 29, 2018 Leave a comment

Questions:

I am trying to make a request to my RESTful API using Android and HttpURLConnection. The data must be sent in the JSON format via POST data.

Here is my code:

JSONObject check_request = new JSONObject();
check_request.put("username", username);

JSONObject request = BuildRequest(check_request, "username_check", false);
Log.i("DEBUG", request.toString());
// DEBUG OUTPUT: {"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}

URL request_url = new URL(apiURL);
HttpURLConnection connection = (HttpURLConnection)request_url.openConnection();
connection.setRequestProperty("User-Agent", "TheGameApp");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);

OutputStream os = connection.getOutputStream();
os.write(request.toString().getBytes("UTF-8"));
os.flush();


InputStream in = new BufferedInputStream(connection.getInputStream());

String result = "";

BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
String str;
while ((str = br.readLine()) != null)
{
    result += str;
}

Log.i("DEBUG", result);

//JSONObject result_json = new JSONObject(result);
os.close();
in.close();
connection.disconnect();

You can see the Debug output as a Comment. The Problem is that the API does not receive any POST data. I have used PHPs var_dump to dump $_POST and $_REQUEST which both are empty arrays.

What am I missing here?

As the question popped up if the API work. This cURL command works fine with the correct result (it is the same JSON data as the debugger printed):

curl -d '{"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}' -H "Content-Type: application/json" -X POST http://localhost/v1/api.php
Answers: