整合第三方 API 的 Service 後,將提供 API 給外部調用,實作使用者是否存在、使用者登入等,輸入 API 參數,發送請求,取得 HTTP 200 回應, EP 22-9 增加範例,並透過 Postman 來驗證產出結果。
Table of Contents
Toggle前言
HttpClient 是一套支援 HTTP 協議的用戶端程式庫,實現了所有 HTTP 的方法,如: GET 、 POST 、PUT 等,以及支援自動轉向與代理服務器等,提供了許多高效率的類別。
Java HttpClient GggAPI
檔案目錄
./
+- build.gradle
+- src
+- main
+- java
+- org
+- ruoxue
+- spring_boot_168
+- game
| +- ggg
| +- api
| | +- GggAPI.java
設定
Server API
網址:http://localhost:10000
Function | Method | Path | Content-Type | Params | Description |
使用者是否存在 | GET | /api/ggg/user/exist | application/x-www-form-urlencoded | username | 使用者名稱 |
password | 密碼 | ||||
Reponse | {"errorCode": 0,"exist": false} | ||||
使用者登入 | POST | /api/ggg/user/login | application/x-www-form-urlencoded | username | 使用者名稱 |
password | 密碼 | ||||
Reponse | {"errorCode":0,"name":"player","token":"0x12345678","exist": true} |
GggService.java
Service 如何建立,參考此篇:
實作
GggAPI.java
調用 Service ,使用 ResponseEntity 回應 HTTP 200,輸出 JSON 格式給前端。
package org.ruoxue.spring_boot_168.game.ggg.api;
import java.util.Locale;
import org.ruoxue.spring_boot_168.game.ggg.ex.GggException;
import org.ruoxue.spring_boot_168.game.ggg.model.GggReponse;
import org.ruoxue.spring_boot_168.game.ggg.service.GggService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
public class GggAPI {
@Autowired
private GggService gggService;
public GggAPI() {
}
/**
* 使用者是否存在
*
* @param webRequest
* @param locale
* @param username
* @param password
* @return
*/
@GetMapping(value = { "/api/ggg/user/exist" })
public ResponseEntity<GggReponse> exist(WebRequest webRequest, Locale locale, @RequestParam String username,
@RequestParam String password) {
ResponseEntity<GggReponse> result = null;
//
try {
boolean ret = gggService.exist(username, password);
GggReponse gggReponse = new GggReponse();
gggReponse.setErrorCode(0);
gggReponse.setExist(ret);
result = ResponseEntity.ok().body(gggReponse);
} catch (GggException ex) {
log.error(ex.getMessage(), ex);
result = ResponseEntity.notFound().build();
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
result = ResponseEntity.notFound().build();
}
return result;
}
/**
* 使用者登入
*
* @param webRequest
* @param locale
* @param username
* @param password
* @return
*/
@PostMapping(value = { "/api/ggg/user/login" })
public ResponseEntity<GggReponse> login(WebRequest webRequest, Locale locale, @RequestParam String username,
@RequestParam String password) {
ResponseEntity<GggReponse> result = null;
//
try {
GggReponse ret = gggService.login(username, password);
result = ResponseEntity.ok().body(ret);
} catch (GggException ex) {
log.error(ex.getMessage(), ex);
result = ResponseEntity.notFound().build();
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
result = ResponseEntity.notFound().build();
}
return result;
}
}
測試
Application.main
在主程式點右鍵執行 Run As -> Java Application,查看 console,Server 已成功啟動,監聽 10000 port。

2022-10-15T19:49:02.606+0800 [main] INFO PostProcessorRegistrationDelegate$BeanPostProcessorChecker#postProcessAfterInitialization:330 - Bean 'org.springframework.retry.annotation.RetryConfiguration' of type [org.springframework.retry.annotation.RetryConfiguration$$EnhancerBySpringCGLIB$$1e891dfb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2022-10-15T19:49:02.621+0800 [main] INFO PostProcessorRegistrationDelegate$BeanPostProcessorChecker#postProcessAfterInitialization:330 - Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$44df88d3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.7.RELEASE)
2022-10-15T19:49:03.677+0800 [main] INFO PropertySourceBootstrapConfiguration#initialize:98 - Located property source: CompositePropertySource {name='consul', propertySources=[ConsulPropertySource {name='config/ruoxue-spring-boot-168/'}, ConsulPropertySource {name='config/application/'}]}
2022-10-15T19:49:03.695+0800 [main] INFO Application#logStartupProfileInfo:647 - No active profile set, falling back to default profiles: default
2022-10-15T19:49:12.682+0800 [main] INFO application#log:2351 - Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-10-15T19:49:12.682+0800 [main] INFO DispatcherServlet#initServletBean:524 - Initializing Servlet 'dispatcherServlet'
2022-10-15T19:49:12.692+0800 [main] INFO DispatcherServlet#initServletBean:546 - Completed initialization in 10 ms
2022-10-15T19:49:12.885+0800 [main] INFO AbstractConnector#doStart:292 - Started ServerConnector@54d60fa1{HTTP/1.1,[http/1.1]}{0.0.0.0:10000}
2022-10-15T19:49:12.886+0800 [main] INFO JettyWebServer#start:156 - Jetty started on port(s) 10000 (http/1.1) with context path '/'
Postman
網址:http://localhost:10000/api/ggg/user/exist

網址:http://localhost:10000/api/ggg/user/login

心得分享
整合第三方 API,提供 Server API 給前端使用,簡化繁瑣的過程,提升開發效率,當使用者登入,檢查第三方使用者是否存在,若不存在則建立使用者,同時同步本地資料庫使用者資訊,然後登入第三方使用者,取得 Token ,大幅地簡化登入第三方流程。