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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With