I am passing a JOSN object from Java to PHP. I am using jdk 1.8 ang WAMP server. Below is the Java code.
import java.io.IOException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
/**
*
* @author PReeeT Dash
*/
public class FromJava
{
public static void main(String[] args) throws IOException
{
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try
{
HttpPost request = new HttpPost("http://localhost/PGP/JSONReq/tophp.php");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex)
{
System.out.println("Error: Cannot Estabilish Connection");
}
finally
{
httpClient.close();
}
}
}
PHP script:
$data = json_decode(file_get_contents("php://input"));
echo($data);
When I run the PHP file it always shows an Empty page. Can anyone please help me understand why is it not working.
When I run the following PHP code it always executes the else condition.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
echo($data);
}
else
{
echo "XXXXXX";
}