【问题标题】:Having problem sending JSON via Httppost in Java, please help在 Java 中通过 Httppost 发送 JSON 时遇到问题,请帮助
【发布时间】:2011-07-10 02:32:46
【问题描述】:

我正在做一个学校项目,该项目需要 JAVA 将一系列条形码发送到 php Web 服务前端。我查看了几个帖子 herehere,并从中获取了一些信息,但我的代码似乎不起作用。

这是我的 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(发帖前)和$_POSTvar_dump($_POST))的内容是什么?
  • se=org.apache.http.entity.StringEntity@1c184f4 和 var_dump($_POST)=null。

标签: java php


【解决方案1】:

看起来你正在做一个原始的 HTTP 帖子,所以 PHP 代码需要考虑到这一点。对于 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);
}
?>

查看此答案和各种链接以获取更多信息:

php curl post json

【讨论】:

  • canuckistani,非常感谢您的帮助,它成功了!您能否简要解释一下为什么我应该使用 file_get_contents 而不是 $_POST?再次感谢!
  • 这一切都在这个手册页中:se2.php.net/wrappers.php。基本上,如果 post 数据没有在 name=value 对中编码,PHP 不会将其解析到 $_POST 数组中。在这种情况下,您需要使用输入流来访问它。
  • 你我也得到了和你们提到的一样的结果。我也很好奇。尽管我已经将其发布为 json。无论如何@canuckistani:非常感谢!
【解决方案2】:

在php模块中

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

在java中

字符串 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("*********");
       }


     }

'['对于java中的JSON对象需要了解

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 2021-02-21
    • 2021-11-04
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多