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

1、明确需要的jar

2、下边是get、post、delete、put例子:

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<String, Object> resultMap = new HashMap<String, Object>(); 
    	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<String, Object> resultMap = new HashMap<String, Object>(); 
    	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<String, Object> resultMap = new HashMap<String, Object>(); 
    	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<String, Object> resultMap = new HashMap<String, Object>(); 
    	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;
	}
	
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值