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