Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java POST request doesn't send variables

Tags:

java

post

php

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?

like image 759
A. Vreeswijk Avatar asked Feb 27 '21 23:02

A. Vreeswijk


1 Answers

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.

like image 54
jccampanero Avatar answered Oct 03 '22 07:10

jccampanero