Code ví dụ gửi http post request bằng Java (HttpClient)

Code ví dụ gửi http post request bằng Java (HttpClient)

(Xem lại: Apache HttpComponents là gì? Ví dụ HttpClient)

HttpClient Posting Request

1. Basic Post

Gửi http post request với form giống như submit form trên html

public static void basicPost(String url) throws ClientProtocolException, IOException {
  CloseableHttpClient client = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost(url);
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("username", "your_username"));
  params.add(new BasicNameValuePair("password", "your_password"));
  httpPost.setEntity(new UrlEncodedFormEntity(params));
  CloseableHttpResponse response = client.execute(httpPost);
  client.close();
}

2. Post với thông tin xác thực

public static void postWithAuth(String url) throws ClientProtocolException, IOException, AuthenticationException {
  CloseableHttpClient client = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost("http://www.example.com");
  UsernamePasswordCredentials creds = new UsernamePasswordCredentials("your_username", "your_password");
  httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
  CloseableHttpResponse response = client.execute(httpPost);
  client.close();
}

3. Post với dữ liệu dạng JSON

Áp dụng cho trường hợp submit dữ liệu định dạng json (thường dùng cho các restful api)

public void postWithJson(String url, String json) throws ClientProtocolException, IOException {
  CloseableHttpClient client = HttpClients.createDefault();
  HttpPost httpPost = new HttpPost(url);
  StringEntity entity = new StringEntity(json);
  httpPost.setEntity(entity);
  httpPost.setHeader("Accept", "application/json");
  httpPost.setHeader("Content-type", "application/json");
  CloseableHttpResponse response = client.execute(httpPost);
  client.close();
}

4. Post với Fluent API

Cách viết ngắn gọn hơn nhiều so với việc sử dụng đối tượng HttpClients

public void postWithFluentAPI() throws ClientProtocolException, IOException {
  HttpResponse response = Request.Post("http://www.example.com")
      .bodyForm(Form.form().add("username", "your_username").add("password", "your_password").build())
      .execute().returnResponse();
}

5. Post với Multipart file, upload file

Phần post với Multipart file, upload file mình sẽ giới thiệu và làm ví dụ ở bài sau.

Demo

Mình sẽ tạo 1 server bằng spring boot cung cấp 2 controller xử lý cho post request trường hợp bình thường và post request cho trường hợp dữ liệu là json.

(Bạn có thể tìm hiểu spring boot tại đây,

hoặc cứ download về và chạy file SpringBootDemoHttpClientApplication.java là nó start server thôi vì mục đích ở đây là server chỉ dùng để test thôi)

Code ví dụ gửi http post request bằng Java (HttpClient)

Controller

package stackjava.com.sbdemohttpclient.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import stackjava.com.sbdemohttpclient.entities.User;

@Controller
public class BaseController {

  @RequestMapping("/")
  public String index() {
    return "index";
  }

  @RequestMapping(value = "/basic-post", method = RequestMethod.POST)
  public String basicPost(HttpServletRequest request, Model model) {
    model.addAttribute("username", request.getParameter("username"));
    model.addAttribute("password", request.getParameter("password"));
    System.out.println("Hello");
    return "result-basic-post";
  }

  @ResponseBody
  @RequestMapping(value = "/json-post", method = RequestMethod.POST)
  public ResponseEntity<String> jsonPost(@RequestBody User user) {
    return new ResponseEntity<String>("JSON Post success! \nHello: " + user.getUsername(), HttpStatus.OK);
  }

}
  • URL: /basic-post xử lý cho trường hợp submit form bình thường và trả về trang result-basic-post.html
  • URL: /json-post xử lý cho trường hợp dữ liệu submit dạng json

File view

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <h2>Index</h2>
  <fieldset>
    <legend>Basic Post:</legend>
    <form action="/basic-post" method="post">
      Username: <input type="text" name="username" /><br/><br/>
      Password: <input type="text" name="password" /><br/><br/>
      <input type="submit" value="submit"/>
    </form>
  </fieldset>
  <br/>
  <fieldset>
    <legend>Post With JSON:</legend>
      Json data: <textarea rows="5" cols="50" id="textAreaJsonData"></textarea> <br/><br/>
      <button id="jsonSubmit" onclick="submitJsonPost()">Submit</button><br/><br/>
      Result: <span id="resultJsonPost" style="color:red"></span>
  </fieldset>
  
  <script>
    function submitJsonPost() {
      var jsonData = document.getElementById('textAreaJsonData').value;
      console.log(jsonData);
      $.ajax({
        type: "POST",
        contentType : "application/json",
        url: "http://localhost:8080/json-post",
        data: jsonData,
        success: function(result,status,xhr){
          $("#resultJsonPost").text(result);
        },
        error: function(xhr,status,error)	{
          $("#resultJsonPost").text('error');
        }
      });
    }
    
  </script>
</body>
</html>

Code ví dụ gửi http post request bằng Java (HttpClient)

Code thực hiện submit form cho Basic Post từ Java với HttpClient:

package stackjava.com.httpclientpost.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class DemoBacicPost {
  public static void main(String[] args) throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8080/basic-post");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", "kai"));
    params.add(new BasicNameValuePair("password", "stackjava.com"));
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse httpResponse = client.execute(httpPost);
    
      System.out.println("Protocol: " + httpResponse.getProtocolVersion());
      System.out.println("Status:" + httpResponse.getStatusLine().toString());
      System.out.println("Content type:" + httpResponse.getEntity().getContentType());
      System.out.println("Locale:" + httpResponse.getLocale());
      System.out.println("Content:");
      String content = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
      System.out.println("--------------------------------------------------------");
      System.out.println(content);

  }
}

Kết quả:

Code ví dụ gửi http post request bằng Java (HttpClient)

Code thực hiện submit json data từ Java với HttpClient:

package stackjava.com.httpclientpost.demo;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class DemoJsonPost {
  public static void main(String[] args) throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8080/json-post");
    
    StringEntity entity = new StringEntity("{\"username\":\"kai\",\"password\":\"xxx\"}");
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpResponse httpResponse = client.execute(httpPost);
    
      System.out.println("Protocol: " + httpResponse.getProtocolVersion());
      System.out.println("Status:" + httpResponse.getStatusLine().toString());
      System.out.println("Content type:" + httpResponse.getEntity().getContentType());
      System.out.println("Locale:" + httpResponse.getLocale());
      System.out.println("Content:");
      String content = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
      System.out.println("--------------------------------------------------------");
      System.out.println(content);

  }
}

Kết quả:

Code ví dụ gửi http post request bằng Java (HttpClient)

Code ví dụ gửi http post request bằng Java (HttpClient) stackjava.com

Okay, done!

Download code ví dụ trên tại đây: SpringBootDemoHttpClient | HttpClientPost

References:

https://hc.apache.org/

https://hc.apache.org/httpcomponents-core-ga/tutorial/html/index.html

https://hc.apache.org/httpcomponents-client-ga/tutorial/html/

stackjava.com