简体   繁体   中英

Unable to receive JSON POST request in PHP

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";
    } 

I do not think this will work.

A PHP script is not "listening" as would a WebService. However, upon receiving the request, the script processes it and try to "print" the result in HTML, not Java.

Fetch the response body your org.apache.http.client instance receives and eg send it to System.out

CloseableHttpResponse response = httpClient.execute(request);
IOUtils.copy(response.getEntity().getContent(), System.out);

For IOUtils use import org.apache.commons.io.IOUtils; In case you're using maven the dependency is

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

You will most likely get the output

Catchable fatal error<:  Object of class stdClass could not be converted to string

because echo($data) doesn't work. json_decode(...) returns a stdClass. Try

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // json_decode(..., true) will return an array instead of a stdClass
    $data = json_decode(file_get_contents("php://input"), true);
    var_export($data);
}
else
{
    var_export($_SERVER['REQUEST_METHOD']);
}

instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM