JAVA/Spring 일반
Spring restTemplate + OkHttp(for http 2 request)
달사자!
2019. 9. 19. 10:49
메모 목적의 글입니다.
19년 9월 기준으로 기존에 자주 사용하던 apache http 컴포넌트에서는 http 2를 정식으로 지원하지 않는 것 같음
현재 개발 기술 스택인 java+spring 환경에서, 애플 APNS와 통신시 http 2로 통신해야해서 통신 모듈을 변경함(java도 가능하면 11로 올리세요. 8에서는 문제 있음)
- okhttp 디펜더시 추가
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.1.0</version>
</dependency>
- Spring restTemplate에 셋팅
private RestTemplate restTemplate = new RestTemplate();
@PostConstruct //init 시점 및 방법은 선호하는 방법에 따라서 셋팅
private void init() {
// @formatter:off
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(7, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(30, 10, TimeUnit.MINUTES)) //커넥션풀 적용
.build();
// @formatter:on
OkHttp3ClientHttpRequestFactory crf = new OkHttp3ClientHttpRequestFactory(client);
restTemplate.setRequestFactory(crf);
}
- 사용하는 소스 예(일부분)
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//ex) Bearer test.test.test
headers.set("Authorization", authorization);
headers.set("apns-id", apnsId); //A canonical UUID that identifies the notification. example UUID is as follows:123e4567-e89b-12d3-a456-42665544000
//If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.
headers.set("apns-expiration", "0");
headers.set("apns-priority", "10"); //The priority of the notification. 10은 즉시, 5는 배터리상태 고려해서 발송
headers.set("apns-topic", apnsTopic);
log.debug("IOS APNS푸시 요청headers\n{}", headers);
Map<String, Object> bodyMap = new HashMap<String, Object>();
bodyMap.put("aps", aPNSPayloadAPS);
String bodyJson = OM.writeValueAsString(bodyMap);
log.debug("IOS APNS푸시 요청bodyJson\n{}", bodyJson);
//http 200 응답이면 API요청 성공
ResponseEntity<String> rslt = restTemplate.exchange(apiURL, HttpMethod.POST, new HttpEntity<String>(bodyJson, headers), String.class);
log.debug("IOS APNS 푸시발송 요청 리턴 결과\n{}", rslt);