java 前端发送json请求_在Java中通过Httppost发送JSON时遇到问题,请帮助

我正在做一个学校项目,该项目要求JAVA将一系列条形码发送到php Web服务前端.我看了几个帖子here和here,并从中获取了一些东西,但是我的代码似乎不起作用.

所以这是我的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文件来记录每个请求.

$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字符串在哪里?

谁能告诉我我在做什么错?我已经在这里停留了一段时间.谢谢!

解决方法:

看起来您正在写原始HTTP帖子,因此PHP代码需要考虑这一点.对于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);

}

?>

请参阅此答案以及各种链接以获取更多信息:

标签:java,php

来源: https://codeday.me/bug/20191208/2093042.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值