Java HTTP POST请求(JSON)到PHP服务器

Java HTTP POST请求(JSON)到PHP服务器,java,php,json,http,request,Java,Php,Json,Http,Request,我有一个应用程序(Java),需要将json发送到php web服务 这是我用JSON发送用户的方法: public void login(User user) throws IOException { Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); String url = "http://localhost/testserveur/in

我有一个应用程序(Java),需要将json发送到php web服务

这是我用JSON发送用户的方法:

public void login(User user) throws IOException {
    Gson gson = new Gson();
     String json = gson.toJson(user);
     System.out.println(json);
      String url = "http://localhost/testserveur/index.php";
     URL obj = new URL(url);
     HttpURLConnection con = (HttpURLConnection)obj.openConnection();

     con.setRequestMethod("POST");
     con.setRequestProperty("json", json);

     con.setDoOutput(true);
     try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
         wr.flush();
     }

     int responseCode = con.getResponseCode();
     System.out.println(responseCode);

 }
和我的php代码:

$string=$_POST['json'];

我试图在数据库中插入,但
$\u POST['json']
不存在。

我没有看到您发布任何内容。将此添加到您的代码中:

String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
这是不对的:

con.setRequestProperty("json", json);
setRequestProperty不用于设置HTTP负载。它用于设置HTTP头。例如,无论如何都应该相应地设置内容类型。像这样:

con.setContentType("application/json");
您将要发布的实际数据进入HTTP正文。您只需将其写入流的末尾(刷新之前):

如果需要转义数据,这取决于您在web服务器上的实现。如果您阅读文章正文并直接将其解释为JSON,则无需转义:

wr.write(json);
如果您通过参数传输一个或多个JSON字符串(看起来像,因为您在服务器上像$_POST['JSON']一样解析它),那么您需要url转义该字符串:

wr.write("json=" + URLEncoder.encode(json, "UTF-8"));
我对php不是很熟悉。在进一步处理收到的json字符串之前,您可能需要在服务器上对该字符串进行url解码。

谢谢您的帮助

这项工作:

公共无效登录(用户)引发IOException{

    Gson gson = new Gson();
    String json = gson.toJson(user);
    System.out.println(json);

    String url = "http://localhost/testserveur/index.php";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("json", json);


    OutputStream os = con.getOutputStream();
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    //wr.write(new String("json=" + json).getBytes());
    String param = "json=" + URLEncoder.encode(json, "UTF-8");
    wr.write(param.getBytes());

    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println(responseCode);

}
PHP:

$string=$_POST['json']


使用调试语法print\r($\u POST)检查收到的信息,并验证您的POST是否成功