http四种请求(get/post/delete/put)

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;
	}
	
}

 

你可能感兴趣的:(Java后端)