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

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

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

Hướng dẫn gửi http request bên trong code Java/ Servlet mà không cần sử dụng server. Ví dụ với HttpClient và Fluent API (Thư viện apache httpcomponents)

Tạo Maven Project

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

Thư viện sử dụng:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>fluent-hc</artifactId>
  <version>4.5.5</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

Thư viện apache.httpcomponents dùng để gửi nhận http request/response

Thư viện commons-io dùng để đọc ghi input/output (vì response nhận về sẽ là 1 stream (data, string, file…) nên mình dùng thư viện common-io đọc dữ liệu cho tiện)

(Xem lại: Đọc/ghi file với Common IO)

Gửi http request với HttpClient

package stackjava.com.httpcomponentsget.demo;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

public class HttpClientGet {
  public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpGet httpGet = new HttpGet("https://www.google.com.vn/");
    HttpClient client = HttpClients.createDefault();
    HttpResponse httpResponse = client.execute(httpGet);
    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("Headers:");
    for(Header header : httpResponse.getAllHeaders()) {
      System.out.println("          " + header.getName()+": " + header.getValue());
    }
    System.out.println("Content:");
    String content = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
    System.out.println(content);
  }
}

HttpGet chứa các thông tin của http get request (url, parameter, header…)

HttpClient thực hiện gửi request

HttpResponse chứa response trả về (gồm protocol, status, conten type, headers… và đối tượng HttpEntity – chứa dữ liệu)

Gửi http request với fluent API

fluent là một api giúp thực hiện việc gửi request một cách nhanh chóng và đơn giản hơn:

package stackjava.com.httpcomponentsget.demo;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;

public class FluentGet {
  public static void main(String[] args) throws ClientProtocolException, IOException {
    Response response = Request.Get("https://www.google.com.vn/").execute();
    HttpResponse httpResponse = response.returnResponse();
    
    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("Headers:");
    for(Header header : httpResponse.getAllHeaders()) {
      System.out.println("          " + header.getName()+": " + header.getValue());
    }
    System.out.println("Content:");
    String content = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
//		String content = response.returnContent().asString();
    System.out.println(content);
    
  }
}

Trường hợp data trả về là String thì ta có thể lấy nội dung bằng response.returnContent().asString(); mà không cần thông qua đối tượng HttpEntity

Demo:

Gửi request tới đường dẫn https://www.google.com.vn/

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

Okay, Done!
Download code ví dụ trên tại đây

 

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