3

I'm working on a school project, which requires JAVA to send a series of barcodes to a php web service front end. I've looked at a couple of posts here and here,and taken something from them, but my code doesn't seem to work.

So here's my JAVA code:

import org.json.simple.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import java.io.InputStream;


public class jsontest2 {
    public static void main (String Args[]) {
        JSONObject obj=new JSONObject();
        JSONObject codes=new JSONObject();
        //Forms the name value pairs for the barcodes and quantity
        codes.put("598013", new Integer(10));
        codes.put("5849632927",new Integer(15));
        codes.put ("5849676037",new Integer(20));
        codes.put ("6634391931", new Integer(25));

        //Headers in the JSON array
        obj.put("LoginID", new Integer(1234));
        obj.put("Machine_ID", new Integer(123456789));
        obj.put("add", codes);
        System.out.print(obj);

        //httppost
        try {
            HttpClient httpclient= new DefaultHttpClient();
            HttpResponse response;
            HttpPost httppost= new HttpPost ("http://example/receive.php");
            StringEntity se=new StringEntity ("myjson: "+obj.toString());
            httppost.setEntity(se);
            System.out.print(se);
            httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Content-type", "application/json");

            response=httpclient.execute(httppost);

        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.print("Cannot establish connection!");
        }
    }
}

And to test the httppost request, I've made this php file to log every request.

<?php
$input = stripslashes($_POST["myjson"]);
logToFile("post.txt", $input);

function logToFile($filename, $msg)
{
    $fd = fopen($filename, "a");
    $str ="[".date("Y/m/d h:i:s")."]".$msg;
    fwrite($fd, $str."\n");
    fclose($fd);
}

The problem is, in log file log.txt, every time I run the JAVA program, it only adds a new line consisting time and date. To me, this means that php is picking up that there was a httppost request, but where is my json string?

Can anyone tell me what am I doing wrong? I've been stuck here for a while. Thanks!

2
  • what is the content of se (before posting) and $_POST (var_dump($_POST))? Commented Mar 7, 2011 at 4:40
  • se=org.apache.http.entity.StringEntity@1c184f4 and var_dump($_POST)=null. Commented Mar 7, 2011 at 4:52

2 Answers 2

3

It looks like you're doing a raw HTTP post, so the PHP code needs to account for that. For the PHP code try this:

<?php
$input = file_get_contents('php://input');
logToFile("post.txt",$input);

function logToFile($filename,$msg)
{
      $fd=fopen($filename,"a");
      $str="[".date("Y/m/d h:i:s")."]".$msg;
      fwrite($fd,$str."\n");
      fclose($fd);
}
?>

See this answer and the various links for more info:

php curl post json

Sign up to request clarification or add additional context in comments.

3 Comments

canuckistani, thanks a lot for your help, it worked! Could you maybe briefly explain why I should've used file_get_contents instead of $_POST? Thanks again!
It's all in this manual page: se2.php.net/wrappers.php. Basically, if the post data isn't encoded in name=value pairs PHP doesn't parse it into the $_POST array. In this case you need to instead access it using the input stream.
ya me too obtaining the same result as you all guys mentioned. I also curious. Eventough I already posting it as json. Anyway @canuckistani: great thanks!
0

In php Module

            $username="demo";
    $action = 'error';
    $json   =array('action'=> $action, 'username' => $username );
    echo json_encode($json);

In java

String regstatus=" ";

  BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));    

     String line;
     while ((line = rd.readLine()) != null) {

       regstatus =line;
       String json="["+regstatus+"]" ;
       JsonArray jArray = new JsonParser().parse(json).getAsJsonArray();
       for (int i=0;i<jArray.size();i++) {
           JsonObject jsonObject = jArray.get(i).getAsJsonObject();
           System.out.println(jsonObject.get("username"));
           System.out.println(jsonObject.get("action"));
           System.out.println("*********");
       }


     }

'[' need to understand for JSON object in java

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.