I am working on a school project that requires JAVA to send a series of barcodes to the php web service interface. I looked at a couple of posts here and here , and took something from them, but my code doesn't seem to work.
So here is 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();
codes.put("598013", new Integer(10));
codes.put("5849632927",new Integer(15));
codes.put ("5849676037",new Integer(20));
codes.put ("6634391931", new Integer(25));
obj.put("LoginID", new Integer(1234));
obj.put("Machine_ID", new Integer(123456789));
obj.put("add", codes);
System.out.print(obj);
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 made this php file to register each 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 the log file log.txt every time the JAVA program starts, it adds only a new line consisting of time and date. For me, this means that php chooses that there is an httppost request, but where is my json line?
Can someone tell me what I am doing wrong? I've been stuck here for a while. Thank!