-
Notifications
You must be signed in to change notification settings - Fork 1
Options
readeyKim edited this page Aug 14, 2019
·
1 revision
HCL은 Request Timeout과 Interceptor에 대한 설정을 제공합니다.
- HttpClient 객체 생성 단계에서
HttpClient.Builder().xxxTimeout(long, TimeUnit)
의 형태로 설정합니다. - 4가지 Timeout을 제공합니다.
- connect timeout
- 요청이 시작된 후 서버와 handshake가 완료될 때까지의 시간
- 기본값은 10초
- read timeout
- 서버와 연결된 후 서버로부터 응답을 받기까지의 시간
- 기본값은 10초
- write timeout
- 서버와 연결된 직후 서버로 바이트를 보내기까지의 시간
- 기본값은 10초
- call timeout
- connect + read + write timeout
- 기본값은 제한없음
HttpClient httpClient = new HttpClient.Builder()
.baseUrl("http://jsonplaceholder.typicode.com")
.readTimeout(1500, TimeUnit.MILLISECONDS)
.build();
- Interceptor를 사용하면 요청과 응답이 완료되기 전에 헤더를 붙이거나 캔슬하는 등의 처리를 할 수 있습니다.
- Interceptor는 Network Interceptor와 Application Interceptor 두 가지 타입이 있습니다.
- 자세한 내용은 okhttp guide 문서에서 확인하실 수 있습니다.
- Interceptor를 사용하기 위해서는 HttpClient 객체 생성단계에서 추가해줘야 합니다.
- Interceptor를 추가하기 위해서는 HCL에서 정의한 Interceptor 인터페이스를 구현해야 합니다.
- Interceptor에 대한 정의는 다음과 같습니다.
public interface Interceptor {
Response intercept(InterceptorChain chain) throws IOException;
}
- intercept의 파라미터 타입인 InterceptorChain 객체의 정의는 다음과 같습니다.
public final class InterceptorChain {
// Request URL을 변경할 수 있습니다.
public void setRequestUrl(String url) {...}
public void setRequestUrl(URL url) {...}
// Request에 포함되는 Header를 추가합니다.
// 이미 값이 있던 경우 이전 데이터는 지워집니다.
public void setRequestHeader(String name, String value) {...}
// Request에 포함되는 Header를 추가합니다.
// 이미 값이 있더라도 이전 데이터가 지워지지 않습니다.
public void addRequestHeader(String name, String value) {...}
// name에 해당하는 Header를 삭제합니다.
public void removeRequestHeader(String name) {...}
// name에 해당하는 Header 값을 읽어옵니다.
public String readRequestHeader(String name) {...}
// 현재 설정된 connect timeout을 밀리세컨 단위로 읽어옵니다.
public int connectTimeoutMills() {...}
// connect timeout을 새로 설정합니다.
public void setConnectTimeout(int timeout, TimeUnit unit) {...}
// 현재 설정된 read timeout을 밀리세컨 단위로 읽어옵니다.
public int readTimeoutMills() {...}
// read timeout을 새로 설정합니다.
public void setReadTimeout(int timeout, TimeUnit unit) {...}
// 현재 설정된 write timeout을 밀리세컨 단위로 읽어옵니다.
public int writeTimeoutMills() {...}
// write timeout을 새로 설정합니다.
public void setWriteTimeout(int timeout, TimeUnit unit) {...}
// Request를 가지고서 서버에 요청하고, 응답 값을 받아옵니다.
public Response proceed() throws IOException {...}
}
- Interceptor 객체 내의 intercept() 메소드는 null을 리턴해서는 안됩니다.
- Network Interceptor는 기존에 설정된 Address의 host와 port는 변경할 수 없습니다.
- Relative URL, Query만 변경 가능합니다.
- Network Interceptor는 chain.proceed()를 오직 한 번만 수행할 수 있습니다.
- Application Interceptor의 경우 Response를 close()하면 재요청 가능합니다.