http 네 가지 요청(get/post/delete/put)

12417 단어 자바 백 엔 드
1.http 요청 에 도입 할 jar 를 명 확 히 합 니 다.
2.방법의 예 는 다음 과 같다.
package com.cmos.clbim.web.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.cmos.core.logger.Logger;
import com.cmos.core.logger.LoggerFactory;

import net.sf.json.JSONObject;

public class HttpClientUtil {
	private static Logger LOGGER = LoggerFactory.getActionLog(HttpClientUtil.class);
	private static final String APPLICATION_JSON = "application/json";
//	private static final String APPLICATION_JSON = "application/json;charset="+"\""+"UTF-8"+"\"";
//  private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
	
	/**
	 * 
	 * @Title      : httpPost 
	 * @Description: TODO
	 * @param url
	 * @param jsonObject
	 * @return     : String
	 * @author     :
	 * Create Date : 2017-9-21   8:51:09
	 * @throws
	 */
	public static String httpPost(String url, String jsonObject) {
		
		CloseableHttpClient httpClient = null;
    	Map resultMap = new HashMap(); 
    	resultMap.put("errorMsg", "      ");
    	JSONObject js = JSONObject.fromObject(resultMap);
    	String result = "";
    	try {
    		LOGGER.info("httpPost => ***---------------     url:------------------------------------"+url);
    		LOGGER.info("httpPost => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
    		LOGGER.info("httpPost => ***---------------     json--------------------------"+jsonObject);
	        //      
    		RequestConfig defaultRequestConfig = RequestConfig.custom()
    				.setSocketTimeout(40000)
    				.setConnectTimeout(40000)
    				.setConnectionRequestTimeout(40000)
    				.build();
    		
	        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
	        
	        
	        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
	        
//	        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000);
//	    	httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000);
	    	
	        HttpPost httpPost = new HttpPost(url);
	        //  hearder  
	        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
//      	StringEntity se = new StringEntity(encoderJson);
//	        StringEntity se = new StringEntity(json);
//	        StringEntity se = new StringEntity(jsonObject,APPLICATION_JSON,"utf-8");
	        
	        StringEntity se = new StringEntity(jsonObject, ContentType.APPLICATION_JSON);
	        
//	        se.setContentType(CONTENT_TYPE_TEXT_JSON);
//	        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
	        httpPost.setConfig(requestConfig);
	        httpPost.setEntity(se);
	        
	        HttpResponse response;
			response = httpClient.execute(httpPost);
	        //          
	        int flag = response.getStatusLine().getStatusCode();
	        if(flag == 200){
	        	LOGGER.info("httpPost => ***---------------       ------------***");
	        	//     
	            //       ,   response.getEntity().getContent()  InputStream
	        	//    
	            //result=new String(result.getBytes("ISO-8859-1"),"GBK");//     GBK
	            result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
	        }else{
	    		result = js.toString();
	    		LOGGER.info("httpPost => ***---------------       ------------***");
	        }
    	} catch (ClientProtocolException e) {
    		result = js.toString();
    		LOGGER.error("httpPost => ***---------------       ------------ClientProtocolException",e);
		} catch (IOException e) {
    		result = js.toString();
    		LOGGER.error("httpPost => ***---------------       ------------IOException",e);
		}finally{
			if(httpClient != null){
				try {
					httpClient.close();
				} catch (IOException e) {
					LOGGER.error("httpPost =>     "+ e);
				}
			}

		}
    	LOGGER.info("httpPost => ***---------------      ------------------------***"+result);
        return result;
	}
	
	
	/**
	 * 
	 * @Title      : httpPut 
	 * @Description: TODO
	 * @param url
	 * @param jsonObject
	 * @return     : String
	 * @author     :
	 * Create Date : 2017-9-22   11:28:26
	 */
	public static String httpPut(String url, String jsonObject) {
		CloseableHttpClient httpClient = null;
    	Map resultMap = new HashMap(); 
    	resultMap.put("errorMsg", "      ");
    	JSONObject js = JSONObject.fromObject(resultMap);
    	String result = "";
    	try {
    		LOGGER.info("httpPut => ***---------------     url:------------------------------------"+url);
    		LOGGER.info("httpPut => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
    		LOGGER.info("httpPut => ***---------------     json--------------------------"+jsonObject);
	        //      
    		RequestConfig defaultRequestConfig = RequestConfig.custom()
    				.setSocketTimeout(40000)
    				.setConnectTimeout(40000)
    				.setConnectionRequestTimeout(40000)
    				.build();
    		
	        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
	        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
	        HttpPut httpPut = new HttpPut(url);
	        //  hearder  
	        httpPut.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
	        StringEntity se = new StringEntity(jsonObject, ContentType.APPLICATION_JSON);
	        httpPut.setConfig(requestConfig);
	        httpPut.setEntity(se);
	        HttpResponse response;
			response = httpClient.execute(httpPut);
	        //          
	        int flag = response.getStatusLine().getStatusCode();
	        if(flag == 200){
	        	LOGGER.info("httpPut => ***---------------       ------------***");
	            result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
	        }else{
	    		result = js.toString();
	    		LOGGER.info("httpPut => ***---------------       ------------***");
	        }
    	} catch (ClientProtocolException e) {
    		result = js.toString();
    		LOGGER.error("httpPut => ***---------------       ------------ClientProtocolException",e);
		} catch (IOException e) {
    		result = js.toString();
    		LOGGER.error("httpPut => ***---------------       ------------IOException",e);
		}finally{
			if(httpClient != null){
				try {
					httpClient.close();
				} catch (IOException e) {
					LOGGER.error("httpPut =>     "+e);
				}
			}
		}
    	LOGGER.info("httpPut => ***---------------      ------------------------***"+result);
        return result;
	}

	/**
	 * 
	 * @Title      : httpGet 
	 * @Description: TODO
	 * @param url   Rest API URL
	 * @return     : String
	 * @author     :
	 * Create Date : 2017-9-22   4:52:06
	 */
	public static String httpGet(String url) {
		CloseableHttpClient httpClient = null;
    	Map resultMap = new HashMap(); 
    	resultMap.put("errorMsg", "      ");
    	JSONObject js = JSONObject.fromObject(resultMap);
    	String result = "";
    	try {
    		LOGGER.info("httpPut => ***---------------     url:------------------------------------"+url);
    		LOGGER.info("httpPut => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
	        //      
    		RequestConfig defaultRequestConfig = RequestConfig.custom()
    				.setSocketTimeout(40000)
    				.setConnectTimeout(40000)
    				.setConnectionRequestTimeout(40000)
    				.build();
    		
	        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
	        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
	        HttpGet httpGet = new HttpGet(url);
	        //  hearder  
	        httpGet.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
	        httpGet.setConfig(requestConfig);
	        HttpResponse response;
			response = httpClient.execute(httpGet);
	        //          
	        int flag = response.getStatusLine().getStatusCode();
	        if(flag == 200){
	        	LOGGER.info("httpGet => ***---------------       ------------***");
	            result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
	        }else{
	    		result = js.toString();
	    		LOGGER.info("httpGet => ***---------------       ------------***");
	        }
    	} catch (ClientProtocolException e) {
    		result = js.toString();
    		LOGGER.error("httpGet => ***---------------       ------------ClientProtocolException",e);
		} catch (IOException e) {
    		result = js.toString();
    		LOGGER.error("httpGet => ***---------------       ------------IOException",e);
		}finally{
			if(httpClient != null){
				try {
					httpClient.close();
				} catch (IOException e) {
					LOGGER.error("httpGet =>     "+ e);
				}
			}
		}
    	LOGGER.info("httpGet => ***---------------      ------------------------***"+result);
        return result;
	}
	
	public static String httpDelete(String url) {
		CloseableHttpClient httpClient = null;
    	Map resultMap = new HashMap(); 
    	resultMap.put("errorMsg", "      ");
    	JSONObject js = JSONObject.fromObject(resultMap);
    	String result = "";
    	try {
    		LOGGER.info("httpDelete => ***---------------     url:------------------------------------"+url);
    		LOGGER.info("httpDelete => ***---------------json Content-Type:---------------"+APPLICATION_JSON);
	        //      
    		RequestConfig defaultRequestConfig = RequestConfig.custom()
    				.setSocketTimeout(40000)
    				.setConnectTimeout(40000)
    				.setConnectionRequestTimeout(40000)
    				.build();
    		
	        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
	        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
	        HttpDelete httpDelete = new HttpDelete(url);
	        //  hearder  
	        httpDelete.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
	        httpDelete.setConfig(requestConfig);
	        HttpResponse response;
			response = httpClient.execute(httpDelete);
	        //          
	        int flag = response.getStatusLine().getStatusCode();
	        if(flag == 200){
	        	LOGGER.info("httpDelete => ***---------------       ------------***");
	            result = EntityUtils.toString(response.getEntity(),Charset.defaultCharset());
	        }else{
	    		result = js.toString();
	    		LOGGER.info("httpDelete => ***---------------       ------------***");
	        }
    	} catch (ClientProtocolException e) {
    		result = js.toString();
    		LOGGER.error("httpDelete => ***---------------       ------------ClientProtocolException",e);
		} catch (IOException e) {
    		result = js.toString();
    		LOGGER.error("httpDelete => ***---------------       ------------IOException",e);
		}finally{
			if(httpClient != null){
				try {
					httpClient.close();
				} catch (IOException e) {
					LOGGER.error("httpDelete =>     "+ e);
				}
			}
		}
    	LOGGER.info("httpDelete => ***---------------      ------------------------***"+result);
        return result;
	}
	
}

좋은 웹페이지 즐겨찾기