1. maven 디펜더시 추가

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.0</version>
</dependency>

 

2. 샘플 소스

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * OKHttp를 이용한 요청 샘플
 * 
 * @author 엄승하
 */
public class OkHttpSample {

	static String reqUrl = "https://www.naver.com";

	//OkHttp를 사용하기 위한 client 생성(기본적으로 new시 커넥션풀 셋팅됨), 1개를 재 사용해야함

	// @formatter:off
	static OkHttpClient client = new OkHttpClient.Builder()
		//default timeout for client annotated requests
		.readTimeout(1000, TimeUnit.MILLISECONDS).connectTimeout(200, TimeUnit.MILLISECONDS).writeTimeout(500, TimeUnit.MILLISECONDS)
		//.addInterceptor(new TimeoutInterceptor())
		.build();

	// @formatter:on

	public static void main(String[] args) {

		reqGetSample();
		reqGetExtendTimeout();
		reqPostSample();

	}

	/**
	 * HTTP Get요청 샘플
	 */
	public static void reqGetSample() {

		try {

			//Request request = new Request.Builder().addHeader("X-ReqSvcCd", "TESTER").addHeader("CloudFront-Viewer-Country", "DE").url(reqUrl).build();
			Request request = new Request.Builder().addHeader("X-ReqSvcCd", "TESTER").url(reqUrl).build();
			Response response = client.newCall(request).execute();
			responseProcess(response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 타임아웃을 늘린 요청(기본 클라이언트는 존재하지만 타임아웃값만 확장)
	 */
	public static void reqGetExtendTimeout() {

		try {
			OkHttpClient extendedTimeoutClient = client.newBuilder().readTimeout(1200, TimeUnit.MILLISECONDS).build(); //해당 요청만 타임아웃 늘림

			Request request = new Request.Builder().addHeader("X-ReqSvcCd", "TESTER").addHeader("CloudFront-Viewer-Country", "DE").url(reqUrl).build();
			Response response = extendedTimeoutClient.newCall(request).execute();
			responseProcess(response);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * HTTP POST 요청 샘플
	 */
	public static void reqPostSample() {

		try {
			RequestBody formBody = new FormBody.Builder().add("user", "tester").build(); //FormBody사용시 content-type는 application/x-www-form-urlencoded
			Request request = new Request.Builder().addHeader("X-ReqSvcCd", "TESTER").url(reqUrl).post(formBody).build();

			Response response = client.newCall(request).execute();
			responseProcess(response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void responseProcess(Response response) throws IOException {

		if (response.isSuccessful()) {
			String rtnMsg = response.body().string();
			System.out.println(String.format("성공. 응답 msg => '%s", rtnMsg));
		} else {
			System.out.println(String.format("응답에러(200이 아님). 응답 code:'%s'\n errMsg:'%s'", response.code(), response.body().string()));
		}

		System.out.println("\n");
	}
}
메모 목적의 글입니다.

19년 9월 기준으로 기존에 자주 사용하던 apache http 컴포넌트에서는 http 2를 정식으로 지원하지 않는 것 같음
현재 개발 기술 스택인 java+spring 환경에서, 애플 APNS와 통신시 http 2로 통신해야해서 통신 모듈을 변경함(java도 가능하면 11로 올리세요. 8에서는 문제 있음)


  1. okhttp 디펜더시 추가
        <dependency>
               <groupId>com.squareup.okhttp3</groupId>
               <artifactId>okhttp</artifactId>
               <version>4.1.0</version>
          </dependency>

  1. 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);
     }


  1. 사용하는 소스 예(일부분)

               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);

+ Recent posts