자바 HTTP 로드밸런싱 서버의 리다이렉션 캡처
HttpUtil.java
이어서 작성한다.
// Apache HttpCore » 4.4.15 필요
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
// Apache HttpClient » 4.5.13 필요
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClients;
import org.apache.http.impl.client.HttpClients;
connectCaptureGET() : GET요청 후 캡처한 응답별 String 얻기
/*********************
* GET 요청 후 타서버 접속하여 응답결과를 String 으로 받는다.
* 타겟 서버측 내부에서 로드밸런싱 등의 리다이렉트 처리가 일어나면
* 중간에서 응답을 캡처한다.
*
* @param 요청 URL주소
* @return String
* @throws IOException
* @throws ClientProtocolException
*********************/
public static String connectCaptureGET(String containParamURL) throws ClientProtocolException, IOException
{
final boolean[] isRedirect = {false};
StringBuilder builder = new StringBuilder();
HttpGet get = null;
// Yarn Resource 서버측 로드밸런싱으로 인한 HTTP 응답 인터셉터 캡처 구현
HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 307) isRedirect[0] = true; //리다이렉트 캡처
}
};
//HttpClient 생성 및 응답 인터셉터 등록
CloseableHttpClient httpClient = HttpClient.custom();
.addInterceptorLast(responseInterceptor);
.build();
try
{
get = new HttpGet(containParamURL);
HttpResponse response = httpClient.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status >= 200 && status < 300)
{
if(isRedirect[0]) return null; //307 로드밸런싱시 return
HttpEntity entity = response.getEntity();
// try-with-resources 자원해제
try (BufferedReader br = new BufferedReader(new InputStreamReader(entitiy.getContent()));) {
String line = null;
while((line = br.readLine()) != null) {
builder.append(line);
}
}
}
}
finally
{
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return builder.toString();
}
Leave a comment