0

I'm sending data to an API from Java using POST.

What I'm trying to do is send a particular variable to the API in the POST request, and then use the value of it. But currently the value is empty. The API is definitely being called.

My Java looks like this:

String line;
StringBuffer jsonString = new StringBuffer();

try {
    URL url = new URL("https://www.x.com/api.php");
    String payload = "{\"variable1\":\"value1\",\"variable2\":\"value2\"}";

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
    writer.write(payload);
    writer.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while ((line = br.readLine()) != null) {
        jsonString.append(line);
    }
    br.close();
    connection.disconnect();
}

This is based on: How to send Request payload to REST API in java?

Currently the value isn't being read correctly. Am I sending it correctly in Java? Do I have to do something to decode it?

2 Answers 2

1

The $_POST variable is not set for all HTTP POST requests, but only for specific types, e.g application/x-www-form-urlencoded.

Since you are posting a request containing JSON entity (application/json), you need to access it as follows.

$json = file_get_contents('php://input');
$entity= json_decode($json, TRUE);
Sign up to request clarification or add additional context in comments.

2 Comments

damn it you were faster xD take my medal!
Look at json_decode() documentation. The second parameter determines whether to return associative array. This should work $entity['variable1'].
0

You can try to use the following code instead of your String variable payload:

List<NameValuePair> payload = new ArrayList<NameValuePair>();

payload.add(new BasicNameValuePair("variable1", "value1");

That worked for me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.