[Java] 3. Apache httpclient - Http API 요청


Apache httpclient - Http API 요청


Apache - httpclient


HTTP 프로토콜을 손쉽게 사용할 수 있도록 도와주는 Apache HTTP 컴포넌트 (HttpClient)이다.
기존의 레거시 프로젝트 때문에 사용 할 수도 있다.


NameValuePair

NameValuePair는 <Key, Value> http 요청시 매개변수이며, List는 <key, value>쌍 의 목록이다.



Http Post 전송

try {
    HttpPost httpPost = new HttpPost("www.example.com/api/board");
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new BasicNameValuePair("param1", "data1"));
    postParams.add(new BasicNameValuePair("param2", "data2"));

    //Post 방식인 경우 데이터를 Request body message에 전송
    HttpEntity postEntity = new UrlEncodedFormEntity(postParams, "UTF-8");
    httpPost.setEntity(postEntity);

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = httpClient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() == 200) {

        ResponseHandler<String> handler = new BasicResponseHandler();
        String body = handler.handleResponse(response);

        //TypeReference<List<BoardModel>> typeReference = new TypeReference<List<BoardModel>>(){};
        //List<BoardModel> boardModelList = objectMapper.readValue(body, typeReference);
        BoardModel boardModel = objectMapper.readValue(body, BoardModel.class);
        log.info("## res boardModel={}", boardModel);
    }
} catch(Exception e) {
    e.printStackTrace();
}



Http Get 전송

try {
    HttpGet httpGet = new HttpGet("www.example.com/api/board?param1=data1&param2=data2");
    httpGet.setHeader("Accept", "application/json");

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = httpClient.execute(httpGet);

    if (response.getStatusLine().getStatusCode() == 200) {

        ResponseHandler<String> handler = new BasicResponseHandler();
        String body = handler.handleResponse(response);

        //TypeReference<List<BoardModel>> typeReference = new TypeReference<List<BoardModel>>(){};
        //List<BoardModel> boardModelList = objectMapper.readValue(body, typeReference);
        BoardModel boardModel = objectMapper.readValue(body, BoardModel.class);
        log.info("## res boardModel={}", boardModel);
    }
} catch(Exception e) {
    e.printStackTrace();
}