2017-02-09 17 views
0

私は広範囲に研究しており解決策を見つけることができません。私は他のユーザーに提供されたソリューションを使用していて、それは私にとってはうまくいかないようです。

私の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を使用しています。 ありがとうございます。

+0

適切なJavaライブラリを使用してHTTPリクエストを作成することをおすすめします。 https://github.com/google/google-http-java-client –

答えて

1

問題は実際にあなたが出力として読むものにあります。 conn.getInputStream();) 1 - 所望の身体

2でPOST要求を送信します)BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); - (空GET要求を送信します!!)へ

変更して:あなたは、2つの要求をしている

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

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

と見ます結果。

+0

それだけです!どうもありがとうございます。 Apacheのログを見ると、あなたは正しいです。私は空のGETを送っていた。 – BaneDad

関連する問題