Sending HTTP POST Request In Java

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

    simplest way to send parameters with the post request:

    String postURL = "http://www.example.com/page.php";
    
    HttpPost post = new HttpPost(postURL);
    
    List params = new ArrayList();
    params.add(new BasicNameValuePair("id", "10"));
    
    UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(ent);
    
    HttpClient client = new DefaultHttpClient();
    HttpResponse responsePOST = client.execute(post);
    

    You have done. now you can use responsePOST. Get response content as string:

    BufferedReader reader = new BufferedReader(new  InputStreamReader(responsePOST.getEntity().getContent()), 2048);
    
    if (responsePOST != null) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(" line : " + line);
            sb.append(line);
        }
        String getResponseString = "";
        getResponseString = sb.toString();
    //use server output getResponseString as string value.
    }
    

提交回复
热议问题