私は広範囲に研究しており解決策を見つけることができません。私は他のユーザーに提供されたソリューションを使用していて、それは私にとってはうまくいかないようです。
私の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を使用しています。 ありがとうございます。
適切なJavaライブラリを使用してHTTPリクエストを作成することをおすすめします。 https://github.com/google/google-http-java-client –