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

时间:2017-02-09 22:33:58

标签: 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 个答案:

答案 0 :(得分:1)

问题实际上在于您所读取的输出。你正在做两个请求: 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()));

并查看结果。