我正在开发一个学校项目,该项目需要JAVA向PHP Web服务前端发送一系列条形码。我查看了几条帖子here和here,并从他们那里拿到了一些东西,但我的代码似乎不起作用。在Java中通过Httppost发送JSON时出现问题,请帮助
因此,这里是我的Java代码:
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!");
}
}
}
,并测试httppost要求,我做了这个PHP文件记录每个请求。
<?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);
}
的问题是,在日志文件log.txt中,我每次运行Java程序时,它只会增加,包括时间和日期的新生产线。对我来说,这意味着PHP正在接受有一个httppost请求,但我的json字符串在哪里?
谁能告诉我我做错了什么?我在这里呆了一段时间。谢谢!
什么是'se'的内容来了解JSON对象(之前发布)和'$ _POST'('的var_dump($ _ POST)')? – 2011-03-07 04:40:11
[email protected]和var_dump($ _ POST)= null。 – 2011-03-07 04:52:04
非常类似于我的情况... – gumuruh 2012-04-18 09:25:53