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