TODAY 0
HTTP 소켓 커넥션 풀

Apache HttpComponents 기반의 서버 사이트 HTTP 통신

왜 Component인가
여기서 이름이 HttpClient -> HttpComponent로 변경되었다는 사실을 생각해봐야 합니다.
왜 Component일까요?
간략하게 설명하자면 HttpClient가 기존과 다르게 작은 모듈과같은 개념으로 재사용가능하게 되었다는 뜻입니다.

# 사용 예제 01
Maven 추가

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.1.2</version>
</dependency>

간단하게 통신하는 메소드 생성

package proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpProxy {
    /**
     * POST 요청
     * @param url       요청할 url
     * @param params    파라메터
     * @param encoding  파라메터 Encoding
     * @return 서버 응답결과 문자열
     */
    public String post(String url, Map params, String encoding){
        HttpClient client = new DefaultHttpClient();
         
        try{
            HttpPost post = new HttpPost(url);
            System.out.println("POST : " + post.getURI());
             
            List<NameValuePair> paramList = convertParam(params);
            post.setEntity(new UrlEncodedFormEntity(paramList, encoding));
             
            ResponseHandler<String> rh = new BasicResponseHandler();
            return client.execute(post, rh);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            client.getConnectionManager().shutdown();
        }
        return "error";
    }
     
    public String post(String url, Map params){
        return post(url, params, "UTF-8");
    }
     
     
     
    /**
     * GET 요청
     * POST 와 동일
     */
    public String get(String url, Map params, String encoding){
        HttpClient client = new DefaultHttpClient();
        try{
            List<NameValuePair> paramList = convertParam(params);
            HttpGet get = new HttpGet(url+"?"+URLEncodedUtils.format(paramList, encoding));
            System.out.println("GET : " + get.getURI());
             
            ResponseHandler<String> rh = new BasicResponseHandler();
             
            return client.execute(get, rh);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            client.getConnectionManager().shutdown();
        }
         
        return "error";
    }
    
    public String get(String url, Map params){
        return get(url, params, "UTF-8");
    }
     
    private List<NameValuePair> convertParam(Map params){
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        Iterator<String> keys = params.keySet().iterator();
        while(keys.hasNext()){
            String key = keys.next();
            paramList.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
         
        return paramList;
    }
     
    // Test
    public static void main(String[] args) {
        HttpProxy p = new HttpProxy();
         
        Map params = new HashMap();
        params.put("w", "tot");
        params.put("q", "한예슬");
         
        System.out.println(p.get("http://m.search.daum.net/search", params));
    }
}

 

# 사용 예제 02
Maven 추가

<dependency>
  <groupid>org.apache.httpcomponents</groupid>
  <artifactid>httpclient</artifactid>
  <version>4.5.2</version>
</dependency>

자바에서 HTTP POST 통신하기

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUtil {
    private static final String DEFAULT_ENCODING = "euc-kr";
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    public HttpUtil() {
    
    }
    public String processHTTP(Map<String, String> params , String url ) throws Exception
    {    
        
        int statusCode = 0;
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);                
        List<NameValuePair> nvps = makeParams(params);
        
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=euc-kr");
            httpPost.setHeader("Cache-Control", "no-cache");
            
            // 한글 인코딩을 위하여 인코딩 정보를 설정한다.
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, DEFAULT_ENCODING));
            
            CloseableHttpResponse response = httpclient.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();
            
            log.debug("\nSending 'POST' request to URL : " + httpPost.getURI());            
            log.debug("Post parameters : " + httpPost.getEntity().toString());
            log.debug("Response Code : " + statusCode );            
            if( statusCode == 200){        
                // 정상인 경우 메시지를 읽어 들여 그 결과를 리턴한다.
                BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }    
                return result.toString();                
            }
            
        } catch (Throwable e) {
            throw new HttpException((new StringBuilder("오류가 발생하였습니다.")).append(statusCode).toString());    
        }        
        if( statusCode != 200)
        {        
            throw new HttpException((new StringBuilder("오류가 발생하였습니다.")).append(statusCode).toString());                
        }
        
    }
    public List<NameValuePair> makeParams(Map<String String> params) throws Exception {
        int hashSize = params.size();
        Iterator keyset = params.keySet().iterator();        
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        for (int i = 0; i < hashSize; i++) {            
            String key = (String) keyset.next();
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
        
        return nvps;
    }
}

 

스프링 사용예제 : https://inyl.github.io/programming/2017/09/14/http_component.html
참고 : http://andang72.blogspot.com/2016/11/apache-httpcomponents-http.html
참고 : https://inyl.github.io/programming/2017/09/14/http_component.html
참고 : http://andang72.blogspot.com/2016/11/apache-httpcomponents-http.html
참고 : http://stove99.tistory.com/26