2

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";
    } 
Pritam
  • 39
  • 5
  • Did you step through with a debugger to make sure all variables are populated? – Ascalonian Feb 29 '16 at 03:50
  • @Ascalonian I am able to print the JSON object in Java. I tried connecting to incorrect URLs to check if the program works. And it produced an exception. Which shows the connection is established successfully. I also tested in the PHP side if it receives a POST request. It fails in receiving the POST request. – Pritam Feb 29 '16 at 03:54

2 Answers2

0

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.

Alexis Ochoa
  • 136
  • 5
  • Yes, I want the script to receive, process and print the result in the browser. Could be PHP or HTML. If you could suggest me any better way that would be nice. – Pritam Feb 29 '16 at 04:02
  • Directly, you can not. You can write the request in a text file or a database and then search for it from PHP. Note that many requests will be many text files or records in the database. `` In another file, `"; } fclose($file); ?>` – Alexis Ochoa Feb 29 '16 at 04:16
  • It is possible using JSON post request. Please check this post http://stackoverflow.com/questions/14983521/send-json-from-java-to-php-through-post – Pritam Feb 29 '16 at 05:10
0

Fetch the response body your org.apache.http.client instance receives and e.g. 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.

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • What should I do if I need to extract data from JSON object and pass it to a PHP function ? – Pritam Mar 01 '16 at 02:07
  • Please one question per question. It's not like Stackoverflow is billing you for creating a question.... – VolkerK Mar 01 '16 at 02:11