HttpClient DELETE - Spring Boot 168 EP 22-4

HttpClient DELETE – Spring Boot 168 EP 22-4

串接第三方 API,使用 HttpClient HttpDelete 發出 DELETE 請求,刪除使用者,返回 HTTP 200 成功,接收所提供的 ErrorCode 等資訊, EP 22-4 增加 GggClient 範例 ,並透過 JUnit 5 來驗證產出結果。

前言

HttpClient 是一套支援 HTTP 協議的用戶端程式庫,實現了所有 HTTP 的方法,如: GET 、 POST 、PUT 等,以及支援自動轉向與代理服務器等,提供了許多高效率的類別。

HttpClient DELETE

檔案目錄

./
   +- build.gradle
       +- src
           +- main
               +- java
                   +- org
                       +- ruoxue
                           +- commons
                               +- httpclient
                                   +- HttpDeleteWithBody.java
                           +- spring_boot_168
                               +- game
                                   +- ggg
                                       +- client
                                       |   +- GggClient.java 
                                       +- ex
                                       |   +- GggException.java 
                                       +- model
                                       |   +- GggReponse.java 

設定

Java HttpClient DELETE JSON

網址:http://ggg.cc:10090
Function Method Path Content-Type Params Description
刪除使用者 DELETE /user application/json;charset=UTF-8 username 使用者名稱
Reponse {"errorCode":0,"name":"player"}

模擬 API,參考此篇:

注入 CloseableHttpClient,如何設定,參考此篇:

實作

GggReponse.java

新增檔案,接收回應,定義 errorCode 、 token 、 name 。

src/main/java/org/ruoxue/spring_boot_168/game/ggg/model/GggReponse.java

package org.ruoxue.spring_boot_168.game.ggg.model;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
public class GggReponse {
	/** 錯誤碼 */
	private int errorCode;
	/** 名稱 */
	private String name;

	@Override
	public String toString() {
		ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
		builder.appendSuper(super.toString());
		builder.append("errorCode", errorCode);
		builder.append("name", name);
		return builder.toString();
	}
}

GggException.java

新增檔案,自定義例外,當發生錯誤時,拋出此例外,讓外層調用的服務,處理例外,如:記錄 Log。

package org.ruoxue.spring_boot_168.game.ggg.ex;

public class GggException extends RuntimeException {

	private static final long serialVersionUID = 2209749235554430258L;

	public GggException() {
		super();
	}

	public GggException(String message) {
		super(message);
	}

	public GggException(Throwable cause) {
		super(cause);
	}

	public GggException(String message, Throwable cause) {
		super(message, cause);
	}
}

HttpDeleteWithBody.java

新增檔案,因 HttpDelete 沒有 setEntity 方法,擴展此功能。

package org.ruoxue.commons.httpclient;

import java.net.URI;
import javax.annotation.concurrent.NotThreadSafe;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

@NotThreadSafe
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
	public static final String METHOD_NAME = "DELETE";

	public String getMethod() {
		return METHOD_NAME;
	}

	public HttpDeleteWithBody(final String uri) {
		super();
		setURI(URI.create(uri));
	}

	public HttpDeleteWithBody(final URI uri) {
		super();
		setURI(uri);
	}

	public HttpDeleteWithBody() {
		super();
	}
}    

HttpClient HttpDelete

自定義 HttpDeleteWithBody,傳入 StringEntity。

GggClient.java

新增檔案,調用第三方 API 客戶端。

package org.ruoxue.spring_boot_168.game.ggg.client;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.ruoxue.commons.httpclient.HttpDeleteWithBody;
import org.ruoxue.spring_boot_168.game.ggg.ex.GggException;
import org.ruoxue.spring_boot_168.game.ggg.model.GggReponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class GggClient {

	/** API 網址 */
	public static final String API_URL = "http://ggg.cc:10090";
	/** 使用者資訊 */
	public static final String USER = "/user";

	@Autowired
	@Qualifier("closeableHttpClient")
	private CloseableHttpClient httpClient;

	private static final Gson gson = new Gson();

	/**
	 * 刪除使用者
	 * 
	 * Content-Type: application/json;charset=UTF-8
	 * 
	 * @param username
	 * @return
	 * @throws Exception
	 */
	public GggReponse delete(String username) throws Exception {
		GggReponse result = null;
		try {
			String requestUrl = API_URL + USER;
			HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(requestUrl);
			httpDelete.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
			JsonObject params = new JsonObject();
			params.addProperty("username", username);
			StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
			httpDelete.setEntity(stringEntity);
			ResponseHandler<String> responseHandler = response -> {
				int status = response.getStatusLine().getStatusCode();
				if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
					HttpEntity entity = response.getEntity();
					return (entity != null ? EntityUtils.toString(entity) : null);
				} else {
					log.error("statusCode: " + status);
					log.error("statusLine: " + response.getStatusLine());
					throw new ClientProtocolException("Unexpected response status: " + status);
				}
			};
			log.info("requestUrl: " + requestUrl);
			String body = httpClient.execute(httpDelete, responseHandler);
			if (StringUtils.isNotEmpty(body)) {
				result = gson.fromJson(body, GggReponse.class);
			} else {
				throw new GggException("ERRORS_NOT_EXIST");
			}

		} catch (Exception ex) {
			throw ex;
		}
		return result;
	}
}

測試 JUnit 5

GggClientTest.java

新增單元測試,驗證是否符合預期 。

package org.ruoxue.spring_boot_168.game.ggg.client;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.ruoxue.spring_boot_168.Application;
import org.ruoxue.spring_boot_168.game.ggg.model.GggReponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Application.class)
public class GggClientTest {

	@Autowired
	private GggClient client;

	@Test
	public void client() {
		System.out.println(client);
		assertNotNull(client);
	}

	@Test
	public void delete() throws Exception {
		GggReponse gggReponse = client.delete("ruoxue");
		System.out.println(gggReponse);
		assertNotNull(gggReponse);
		assertEquals(0, gggReponse.getErrorCode());
	}
}

delete

測試方法上點右鍵執行 Run As -> JUnit Test ,查看 console 。

2022-07-18T15:39:03.321+0800 [main] INFO GggClient#user:59 - requestUrl: http://ggg.cc:10090/user
{"errorCode":0,"name":"player"}

心得分享

使用 Nginx 模擬第三方 API,來協助快速開發,從連接池取得連線,建立 Apache HttpDelete ,設定 Content-Type ,及增加請求參數, 發送 DELETE 請求,然後會返回一個 HttpResponse 物件,封裝了 Server 的回應,並且可以透過該物件取得 HTTP 狀態碼,回應內容等。

發佈留言