Sean Sun
Sean Sun

Reputation: 33

Having problem sending JSON via Httppost in Java, please help

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!

Upvotes: 3

Views: 7435

Answers (2)

sathya
sathya

Reputation: 25

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

Upvotes: 0

therealjeffg
therealjeffg

Reputation: 5830

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

Upvotes: 3

Related Questions