Programing/Java

Apache HttpClient Example

BUST 2018. 7. 29. 12:07

Apache Http Client Example

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