A. Vreeswijk
A. Vreeswijk

Reputation: 954

Java POST request doesn't send variables

I have a problem. I have the following PHP page:

<?php

    header('Content-Type: application/json');
    
    echo $_POST["agentid"];

?>

And my Java code is the following:

public String callWebpage(String strUrl, HashMap<String, String> data) throws InterruptedException, IOException {

    var objectMapper = new ObjectMapper();
    String requestBody = objectMapper
            .writeValueAsString(data);

    URL url = new URL(strUrl);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setDoOutput(true);
    con.getOutputStream().write(requestBody.getBytes("UTF-8"));
    String result = convertInputStreamToString(con.getInputStream());
    return result;
}

To call the function, I use the following lines:

var values = new HashMap<String, String>() {{
    put("agentid", String.valueOf(agentId));
}};

String jsonResponse = webAPI.callWebpage("https://www.test.org/test.php", values);

This does print the result of the page, but it gives me:

2021-02-28 00:40:16.735 Custom error: [8] Undefined index: agentid<br>2021-02-28 00:40:16.735 Error on line 5

The page is HTTPS and I do get a response, but why is my agentid variable not getting received by the page and how can I fix this?

Upvotes: 6

Views: 442

Answers (2)

jccampanero
jccampanero

Reputation: 53381

Please, consider including the following code in your Java connection setup to indicate that you are POSTing JSON content before writing to the connection output stream:

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

In any way, I think the problem is in your PHP code: you are trying to process raw HTTP parameter information while you are receiving a JSON fragment as the request body instead.

In order to access the raw JSON information received in the HTTP request you need something like the following:

// Takes raw data from the request.
$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json);

// Process information
echo $data->agentid; 

Please, see this link and 'php://input` for more information.

Be aware that with the above-mentioned code you are returning a String to the Java client, although you indicated header('Content-Type: application/json'), maybe it could be the cause of any problem.

Upvotes: 7

RoboFlow
RoboFlow

Reputation: 22

I think that you are using HTTP Request. Then, use exec‌‌‌​​‌​‌‌​‌‌‌‌‌‌​​​‌​‌‌​‌‌‌‌ instead of POST if that coder is persist the same as in the answer below.

Upvotes: -2

Related Questions