Sending HTTP POST Request In Java

后端 未结 8 1297
清歌不尽
清歌不尽 2020-11-21 11:17

lets assume this URL...

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

(Here id needs to be sent in a POST request)

I want to se

8条回答
  •  渐次进展
    2020-11-21 11:39

    Updated Answer:

    Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.

    By the way, you can access the full documentation for more examples here.

    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");
    
    // Request parameters and other properties.
    List params = new ArrayList(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
        }
    }
    

    Original Answer:

    I recommend to use Apache HttpClient. its faster and easier to implement.

    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.
    

    for more information check this url: http://hc.apache.org/

提交回复
热议问题