Java
OkHttpClient 요청 메시지에 쿼리 파라미터 추가하기
jayden-lee
2019. 5. 10. 16:30
728x90
OkHttp3 종속성 추가
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.1</version>
</dependency>
쿼리 파라미터 추가한 Request 객체 생성
HttpUrl.Builder 클래스와 addQueryParameter 메서드를 이용하면 쿼리 파라미터를 쉽게 추가할 수 있다. 완성된 URL 문자열 값을 Request 객체를 생성하는 빌더에 넣어주면 된다.
private static MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
public static Request createPostRequest(String url, Map<String, String> params, String bodyJson) {
HttpUrl.Builder httpBuilder = HttpUrl.get(url).newBuilder();
if (CollectionUtils.isNullOrEmpty(params)) {
for (Map.Entry<String, String> param : params.entrySet()) {
httpBuilder.addQueryParameter(param.getKey(), param.getValue());
}
}
return new Request.Builder()
.post(RequestBody.create(JSON_MEDIA_TYPE, bodyJson))
.url(httpBuilder.build())
.build();
}
참고자료
- https://stackoverflow.com/questions/30142626/how-to-add-query-parameters-to-a-http-get-request-by-okhttp
- https://square.github.io/okhttp/