GP Coder

Trang chia sẻ kiến thức lập trình Java

  • Java Core
    • Basic Java
    • OOP
    • Exception Handling
    • Multi-Thread
    • Java I/O
    • Networking
    • Reflection
    • Collection
    • Java 8
  • Design pattern
    • Creational Pattern
    • Structuaral Pattern
    • Behavior Pattern
  • Web Service
    • SOAP
    • REST
  • JPA
  • Java library
    • Report
    • Json
    • Unit Test
  • Message Queue
    • ActiveMQ
    • RabbitMQ
  • All
Trang chủ Java Webservice REST Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries

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

Đăng vào 12/07/2019 . Được đăng bởi GP Coder . 3216 Lượt xem . Toàn màn hình

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.

Nội dung

  • 1 Các bước thực hiện
  • 2 Ví dụ tạo ứng dụng Java RESTful Client sử dụng java.net

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ó).

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.

4.2
05
Nếu bạn thấy hay thì hãy chia sẻ bài viết cho mọi người nhé! Và Donate tác giả

Shares

Chuyên mục: Java Webservice, REST Được gắn thẻ: REST, Webservice

REST Web service: JWT – Token-based Authentication trong Jersey 2.x
Tạo ứng dụng Java RESTful Client với thư viện OkHttp

Có thể bạn muốn xem:

  • REST Web service: JWT – Token-based Authentication trong Jersey 2.x (10/07/2019)
  • Giới thiệu Castle Mock – Mock REST APIs và SOAP web-services (05/09/2019)
  • Giới thiệu SOAP UI và thực hiện test Web Service (30/05/2019)
  • Giới thiệu Json Web Token (JWT) (08/07/2019)
  • Test REST Web Service đơn giản hơn với REST Assured (26/08/2019)

Bình luận

bình luận

Tìm kiếm

Bài viết mới

  • Clean code 13/01/2024
  • Giới thiệu CloudAMQP – Một RabbitMQ server trên Cloud 02/10/2020
  • Kết nối RabbitMQ sử dụng Web STOMP Plugin 19/06/2020
  • Sử dụng publisher confirm trong RabbitMQ 16/06/2020
  • Sử dụng Dead Letter Exchange trong RabbitMQ 13/06/2020

Xem nhiều

  • Hướng dẫn Java Design Pattern – Factory Method (98127 lượt xem)
  • Hướng dẫn Java Design Pattern – Singleton (97743 lượt xem)
  • Giới thiệu Design Patterns (87897 lượt xem)
  • Lập trình đa luồng trong Java (Java Multi-threading) (86515 lượt xem)
  • Giới thiệu về Stream API trong Java 8 (83911 lượt xem)

Nội dung bài viết

  • 1 Các bước thực hiện
  • 2 Ví dụ tạo ứng dụng Java RESTful Client sử dụng java.net

Lưu trữ

Thẻ đánh dấu

Annotation Authentication Basic Java Behavior Pattern Collection Creational Design Pattern Cấu trúc điều khiển Database Dependency Injection Design pattern Eclipse Exception Executor Service Google Guice Gson Hibernate How to Interceptor IO Jackson Java 8 Java Core JDBC JDK Jersey JMS JPA json JUnit JWT Message Queue Mockito Multithreading OOP PowerMockito RabbitMQ Reflection Report REST SOAP Structuaral Pattern Swagger Thread Pool Unit Test Webservice

Liên kết

  • Clean Code
  • JavaTpoint
  • Refactoring Guru
  • Source Making
  • TutorialsPoint
  • W3Schools Online Web Tutorials

Giới thiệu

GP Coder là trang web cá nhân, được thành lập với mục đích lưu trữ, chia sẽ kiến thức đã học và làm việc của tôi. Các bài viết trên trang này chủ yếu về ngôn ngữ Java và các công nghệ có liên quan đến Java như: Spring, JSF, Web Services, Unit Test, Hibernate, SQL, ...
Hi vọng góp được chút ít công sức cho sự phát triển cộng đồng Coder Việt.

Donate tác giả

Tìm kiếm các bài viết của GP Coder với Google Search

Liên hệ

Các bạn có thể liên hệ với tôi thông qua:
  • Trang liên hệ
  • Linkedin: gpcoder
  • Email: contact@gpcoder.com
  • Skype: ptgiang56it

Follow me

Copyright 2025 © GP Coder · All Rights Reserved · Giới thiệu · Chính sách · Điều khoản · Liên hệ ·

Share

Blogger
Delicious
Digg
Email
Facebook
Facebook messenger
Flipboard
Google
Hacker News
Line
LinkedIn
Mastodon
Mix
Odnoklassniki
PDF
Pinterest
Pocket
Print
Reddit
Renren
Short link
SMS
Skype
Telegram
Tumblr
Twitter
VKontakte
wechat
Weibo
WhatsApp
X
Xing
Yahoo! Mail

Copy short link

Copy link