Sending HTTP POST Request In Java

后端 未结 8 1288
清歌不尽
清歌不尽 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:49

    The first answer was great, but I had to add try/catch to avoid Java compiler errors.
    Also, I had troubles to figure how to read the HttpResponse with Java libraries.

    Here is the more complete code :

    /*
     * Create the POST request
     */
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://example.com/");
    // Request parameters and other properties.
    List params = new ArrayList();
    params.add(new BasicNameValuePair("user", "Bob"));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    }
    /*
     * Execute the HTTP Request
     */
    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity respEntity = response.getEntity();
    
        if (respEntity != null) {
            // EntityUtils to get the response content
            String content =  EntityUtils.toString(respEntity);
        }
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();
    }
    

提交回复
热议问题