JavaでHTTP POSTリクエストを送信する質問する

JavaでHTTP POSTリクエストを送信する質問する

この URL の場合:

http://www.example.com/page.php?id=10            

id = 10をサーバーの に送信しpage.php、POST メソッドでそれを受け取りたいです。

Java でこれを実行するにはどうすればよいですか?

これを試してみました:

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

しかし、POST メソッドで送信する方法がまだわかりません。

ベストアンサー1

更新された回答

元の回答の一部のクラスは、Apache HTTP コンポーネントの新しいバージョンでは非推奨になっているため、この更新を投稿します。

ちなみに、より多くの例については完全なドキュメントにアクセスしてください。ここ

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.example/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}

元の回答

Apache HttpClient を使用することをお勧めします。実装が高速かつ簡単です。

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

詳細については、次の URL を参照してください。http://hc.apache.org/

おすすめ記事