Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries

1397

Bài viết được sự cho phép của tác giả Giang Phan

Trong bài này tôi sẽ giới thiệu với các bạn cách gọi Restful web service sử dụng thư viện chuẩn java.net của Java, không sử dụng bất kỳ 3rd party libraries nào khác.

Các bước thực hiện

Để gọi restful web service thông qua lớp java.net chúng ta lần lượt thực hiện các bước sau:

  • Tạo 1 java.net.URL object.
  • Mở HttpURLConnection từ URL trên.
  • Set các Request property cần thiết.
  • Gửi Request data lên server (nếu có).
  • Nhận Response từ server gửi về (nếu có).
  10 lý do cho thấy tại sao bạn nên theo học ngôn ngữ lập trình Java
  10 tips để trở thành Java Developer xịn hơn

Xem thêm chương trình tuyển dụng Java lương cao trên TopDev

Ví dụ tạo ứng dụng Java RESTful Client sử dụng java.net

Trong ví dụ này, chúng ta sẽ gọi lại các Restful API chúng ta đã tạo ở bài viết trước “JWT – Token-based Authentication trong Jersey 2.x“.

Đầu tiên, chúng ta cần gọi API /auth để lấy token và sau đó chúng ta sẽ attach token này vào mỗi request để truy cập resource.

package com.gpcoder;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClientExample {

public static final String BASE_URL = "http://localhost:8080/RestfulWebServiceExample/rest";
private static String token;

public static void main(String[] args) throws IOException {
token = getToken();
System.out.println("token: " + token);

createOrder();
retrieveOrder();
updateOrder();
deleteOrder();
}

/**
* @POST http://localhost:8080/RestfulWebServiceExample/rest/auth
*/
private static String getToken() throws IOException {
// Create A URL Object
URL url = new URL(BASE_URL + "/auth");

// Open a Connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set the Request Content-Type Header Parameter
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// Set Response Format Type
connection.setRequestProperty("Accept", "application/json");

// Set the Request Method
connection.setRequestMethod("POST");

// Create the Request Body and Send post request
String urlParameters = "username=gpcoder&password=gpcoder";
sendRequest(connection, urlParameters);

// Read the Response from Input Stream
return getResponse(connection);
}

private static void sendRequest(HttpURLConnection connection, String data) throws IOException {
// Ensure the Connection Will Be Used to Send Content
connection.setDoOutput(true);

// Create the Request Body and Send post request
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(data);
wr.flush();
}
}

private static String getResponse(HttpURLConnection connection) throws IOException {
int responseCode = connection.getResponseCode();
System.out.println("Response Code : " + responseCode);

StringBuilder response = new StringBuilder();
try (InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));) {
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
}
return response.toString();
}

/**
* @POST http://localhost:8080/RestfulWebServiceExample/rest/orders
*/
private static void createOrder() throws IOException {
// Create A URL Object
URL url = new URL(BASE_URL + "/orders");

// Open a Connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set Authorization header
connection.setRequestProperty("Authorization", "Bearer " + token);

// Set the Request Content-Type Header Parameter
connection.setRequestProperty("Content-Type", "application/json");

// Set the Request Method
connection.setRequestMethod("POST");

// Create the Request Body and Send post request
String data = "{"id" : 1, "name": "gpcoder"}";
sendRequest(connection, data);

// Read the Response from Input Stream
String response = getResponse(connection);
System.out.println("createOrder: " + response);
}

/**
* @GET http://localhost:8080/RestfulWebServiceExample/rest/orders/1
*/
private static void retrieveOrder() throws IOException {
// Create A URL Object
URL url = new URL(BASE_URL + "/orders/1");

// Open a Connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set Authorization header
connection.setRequestProperty("Authorization", "Bearer " + token);

// Set the Request Method
connection.setRequestMethod("GET");

// Read the Response from Input Stream
String response = getResponse(connection);
System.out.println("retrieveOrder: " + response);
}

/**
* @PUT http://localhost:8080/RestfulWebServiceExample/rest/orders
*/
private static void updateOrder() throws IOException {
// Create A URL Object
URL url = new URL(BASE_URL + "/orders");

// Open a Connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set Authentication header
connection.setRequestProperty("Authorization", "Bearer " + token);

// Set the Request Content-Type Header Parameter
connection.setRequestProperty("Content-Type", "application/json");

// Set the Request Method
connection.setRequestMethod("PUT");

// Create the Request Body and Send post request
String data = "{"id" : 1, "name": "gpcoder"}";
sendRequest(connection, data);

// Read the Response from Input Stream
String response = getResponse(connection);
System.out.println("updateOrder: " + response.toString());
}

/**
* @DELETE http://localhost:8080/RestfulWebServiceExample/rest/orders/1
*/
private static void deleteOrder() throws IOException {
// Create A URL Object
URL url = new URL(BASE_URL + "/orders/1");

// Open a Connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set Authorization header
connection.setRequestProperty("Authorization", "Bearer " + token);

// Set the Request Method
connection.setRequestMethod("DELETE");

// Read the Response from Input Stream
String response = getResponse(connection);
System.out.println("deleteOrder: " + response);
}
}

Chạy chương trình trên, chúng ta có kết quả như sau:

Response Code : 200
token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJncGNvZGVyIiwicm9sZXMiOlsiQWRtaW4iLCJDdXN0b21lciJdLCJqdGkiOiIwNWQwZTE5ZS1lODYzLTQ5MGQtOGE0Yi1mZWE4NWQ0OTZhYzIiLCJpYXQiOjE1NjE4MTgxMTgsImlzcyI6Imh0dHBzOi8vZ3Bjb2Rlci5jb20iLCJleHAiOjE1NjE4MTk5MTh9.fhhogziLVLMGz_nZjpFy9N0-MG2t4fOYKl6LSU7tLxo
Response Code : 200
createOrder: OrderService->insert()
Response Code : 200
retrieveOrder: OrderService->get()
Response Code : 200
updateOrder: OrderService->update()
Response Code : 200
deleteOrder: OrderService->delete()

Lưu ý: toàn bộ các API trả về kết quả là plain/text nên tôi không cần xử lý gì thêm. Nếu API các bạn nhận được là một chuỗi json, các bạn có thể sử dụng các thư viện như Gson hay Jackson để convert json về java object.

Trên đây là ví dụ đơn giản để gọi các Restful API sử dụng thư viện chuẩn java.net. Trong các dự án người ta thường ít sử dụng cách này do viết khá dài dòng và phức tạp. Trong các bài viết tiếp theo, tôi sẽ giới thiệu với các bạn các thư viện rất đơn giản và hiệu quả để tạo ứng dụng Java RESTful Client như Jersey client, OkHttp, Retrofit, Feign.

Bài viết gốc được đăng tải tại gpcoder.com

Có thể bạn quan tâm:

Xem thêm công việc IT hấp dẫn trên TopDev