So I'm sending data to a PHP 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 in my PHP. But currently in the PHP, $_POST["variable1"] is empty.
The script is definitely being called, as I'm sent an email each time it is, but the PHP isn't reading the POST variable.
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?
And the PHP API contains this:
if (isset($_POST["variable1"]) && isset($_POST["variable2"])) {
//Send email containing POST values
//Send 200 success header
} else {
//Send error email
//Send 400 error header
}
Currently I get the error email each time I run the Java code. So it is sending to the API, but the value isn't being read correctly.
Am I sending it correctly in Java? Or am I missing something in the PHP? Do I have to do something to decode it?
Thanks for any help. I've been working on this for a while and just can't seem to work out what the issue is.