Apache Http Client Example
- Apache Http Client Example
- https://hc.apache.org/
- Sample Code : https://hc.apache.org/httpcomponents-client-ga/examples.html
- Spring RestTemplate 보다 설정이나 사용이 까다롭다. 설정이 많이 필요한 경우를 제외하고는 Spring RestTemplate를 활용하자.
Sample Code
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://httpbin.org/");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}
}
}
- ResponseHandler로 이용하여 response body를 얻을수가 있다.
'Programing > Java' 카테고리의 다른 글
Rule Engine (0) | 2018.08.04 |
---|---|
Adapter Pattern (0) | 2018.08.01 |
Java Object 비교 == (0) | 2018.07.25 |
Spring RestTemplate (0) | 2018.07.22 |
Spock Framework을 이용한 Unit test 작성 (0) | 2018.06.25 |