Java 客户端 POST 到 php 脚本 - 空 $_POST

标签 java php

我进行了广泛的研究,但找不到解决方案。我一直在使用向其他用户提供的解决方案,但它似乎对我不起作用。

我的java代码:

public class Post {
public static void main(String[] args) { 
    String name = "Bobby";
    String address = "123 Main St., Queens, NY";
    String phone = "4445556666";

    String data = "";
    try { 
        // POST as urlencoded is basically key-value pairs
        // create key=value&key=value.... pairs
        data += "name=" + URLEncoder.encode(name, "UTF-8");
        data += "&address=" + 
            URLEncoder.encode(address, "UTF-8");
        data += "&phone=" + 
            URLEncoder.encode(phone, "UTF-8");

        // convert string to byte array, as it should be sent
        byte[] dataBytes = data.toString().getBytes("UTF-8");

        // open a connection to the site
        URL url = new URL("http://xx.xx.xx.xxx/yyy.php");
        HttpURLConnection conn = 
            (HttpURLConnection) url.openConnection();

        // tell the server this is POST & the format of the data.
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        conn.setRequestMethod("POST");
        conn.setFixedLengthStreamingMode(dataBytes.length);
        conn.getOutputStream().write(dataBytes);

        conn.getInputStream();
        // Print out the echo statements from the php script
        BufferedReader in = new BufferedReader(
                new InputStreamReader(url.openStream()));

        String line;
        while((line = in.readLine()) != null) 
            System.out.println(line);

        in.close();
    } catch(Exception e) { 
        e.printStackTrace();
    }
}
}

和 PHP

<?php
echo $_POST["name"];
?>

我收到的输出是一个空行。我通过制作一个 html 表单来测试这是否是 php/服务器端问题,该表单将数据发送到类似的脚本并将数据打印在屏幕上,并且有效。但是,在我的一生中,我无法让它与远程客户端一起工作。 我正在使用 Ubuntu 服务器和 Apache。 预先感谢您。

最佳答案

问题实际上在于您所读取的输出内容。您正在执行两个请求: 1)conn.getInputStream(); - 发送带有所需正文的 POST 请求

2)BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); - 发送空 GET 请求 (!!)

将其更改为:

// ...
conn.getOutputStream().write(dataBytes);

BufferedReader in = new BufferedReader(
         new InputStreamReader(conn.getInputStream()));

并查看结果。

关于Java 客户端 POST 到 php 脚本 - 空 $_POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148158/

相关文章:

java - JavaFX 程序何时调用启动方法?

php - 无法使用 symfony 和 doctrine 及其关联对象或表保存到 postgresql 中?

javascript - 重定向实时网站访问者而不刷新或单击任何内容?

php - ip blocker 类阻止 "crawl-66-249-76-64.googlebot.com",这是正确的吗?

Java 最终数组列表

java - 使用 Elastic Search 6.2.3 在 AWS EC2 上运行 Spring Boot 2.0.3 应用程序

java - 索引越界异常

php - 验证失败后 FormRequest 不填充 $request->old()

php - Symfony2控制台必须选择mac

java - 本地分析需要 Sonar 3.6 版本