HttpUtils http请求工具类

后台开发经常会调用第三方的接口,整理一个HttpUtils,以后用到直接copy....

package com.yfq360.yfq.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;


public final class HttpUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * @param getUrl     请求地址
     * @param params 提交的请求参数
     */
    public static String get(String getUrl, Map<String, String> params) {
        return get(getUrl, params, "UTF-8");
    }

    public static String get(String getUrl, Map<String, String> params, String charset) {
        return get(getUrl, charset, map2NameValuePair(params));
    }

    public static String get(String getUrl, NameValuePair... parameters) {
        return get(getUrl, "UTF-8", parameters);
    }

    public static String get(String getUrl, String charset, NameValuePair... parameters) {
        return get(getUrl, 10000, 30000, charset, parameters);
    }

    public static String get(String url, int connTimeout, int soTimeout, String charset, NameValuePair... parameters) {
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException("get请求地址不能为空");
        } else {
            GetMethod httpGet = null;
            String respTxt = null;
            try {
                HttpClient httpClient = new HttpClient();
                HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();
                httpConnectionManagerParams.setConnectionTimeout(connTimeout);
                httpConnectionManagerParams.setSoTimeout(soTimeout);
                httpGet = new GetMethod(url);
                httpGet.setRequestHeader("Content-Type", "text/html;charset=" + charset);

                if (null != parameters && parameters.length > 0) {
                    httpGet.setQueryString(parameters);
                }
                int respCode = httpClient.executeMethod(httpGet);
                if (respCode == HttpStatus.SC_OK) {
                    respTxt = httpGet.getResponseBodyAsString();
                }
            } catch (Exception e) {
                logger.error(String.format("HttpUtils.get:httpGet请求发生异常:地址:%s, parameters:%s", url, parameters == null ? null : JsonUtils.toJson(parameters)), e);
            } finally {
                if (httpGet != null)
                    httpGet.releaseConnection();
            }

            return respTxt;
        }
    }

    public static String post(String postUrl, Map<String, String> params) {
        return post(postUrl, params, "UTF-8");
    }

    public static String post(String postUrl, Map<String, String> params, String charset) {
        return post(postUrl, charset, map2NameValuePair(params));
    }

    public static String post(String postUrl, NameValuePair... parameters) {
        return post(postUrl, "UTF-8", parameters);
    }

    public static String post(String postUrl, String charset, NameValuePair... parameters) {
        return post(postUrl, 10000, 30000, charset, parameters);
    }

    public static String post(String postUrl, int connTimeout, int soTimeout, String charset, NameValuePair... parameters) {
        PostMethod httpPost = null;
        String respTxt = null;
        try {
            HttpClient httpClient = new HttpClient();
            HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();
            httpConnectionManagerParams.setConnectionTimeout(connTimeout);
            httpConnectionManagerParams.setSoTimeout(soTimeout);
            httpPost = new PostMethod(postUrl);
            httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
            if (parameters != null && parameters.length > 0) {
                httpPost.addParameters(parameters);
            }
            int respCode = httpClient.executeMethod(httpPost);
            if (respCode == HttpStatus.SC_OK) {
                respTxt = httpPost.getResponseBodyAsString();
            }
        } catch (Exception ex) {
            logger.error(String.format("HttpUtils.post:httpPost请求发生异常:地址:%s, parameters:%s", postUrl, parameters), ex);
        } finally {
            if (httpPost != null)
                httpPost.releaseConnection();
        }
        return respTxt;
    }

    public static String postWithBody(String postUrl, int connTimeout, int soTimeout, RequestEntity requestEntity) {
        return postWithBody(postUrl, connTimeout, soTimeout, requestEntity, false);
    }

    public static String postWithBody(String postUrl, int connTimeout, int soTimeout, RequestEntity requestEntity, boolean isHttps, Header... headers) {
        PostMethod httpPost = null;
        String respTxt = null;
        try {
            if(isHttps){
                Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);
                Protocol.registerProtocol("https", https);
            }
            HttpClient httpClient = new HttpClient();
            HttpConnectionManagerParams httpConnectionManagerParams = httpClient.getHttpConnectionManager().getParams();
            httpConnectionManagerParams.setConnectionTimeout(connTimeout);
            httpConnectionManagerParams.setSoTimeout(soTimeout);
            httpPost = new PostMethod(postUrl);
            httpPost.setRequestEntity(requestEntity);
            if(headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    httpPost.addRequestHeader(headers[i]);
                }
            }
            int respCode = httpClient.executeMethod(httpPost);
            if (respCode == HttpStatus.SC_OK) {
                respTxt = httpPost.getResponseBodyAsString();
            }else{
                logger.error("HttpUtils.postWithBody: 请求失败, 地址:{}, parameters:{}, HttpStatus: {}", postUrl, requestEntity, respCode);
            }
        } catch (Exception ex) {
            logger.error(String.format("HttpUtils.postWithBody:httpPost请求发生异常:地址:%s, parameters:%s", postUrl, requestEntity), ex);
        } finally {
            if (httpPost != null)
                httpPost.releaseConnection();
            if(isHttps){
                Protocol.unregisterProtocol("https");
            }
        }
        return respTxt;
    }

    public static boolean isFromMobile(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        return isFromMobile(userAgent);
    }

    public static boolean isFromMobile(String userAgent) {
        return userAgent.toLowerCase().matches(".+(iphone|ipod|android|ios|ipad).+");
    }

    private static NameValuePair[] map2NameValuePair(Map<String, String> params){
        NameValuePair[] parameters = null;
        if(params != null && params.size() > 0){
            parameters = new NameValuePair[params.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters[i++] = new NameValuePair(entry.getKey(), entry.getValue());
            }
        }
        return parameters;
    }

    
    public static String postBusiBody(String postUrl, int connTimeout, int soTimeout, String charset, JSONObject json) {
		 RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(soTimeout) .setConnectTimeout(connTimeout)
		    .setConnectionRequestTimeout(connTimeout).setStaleConnectionCheckEnabled(true).build();
		 CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
         HttpPost post = new HttpPost(postUrl);
         String paramsStr = json.toString().replaceAll("\\\\\\\\", "\\\\");
         StringEntity myEntity = new StringEntity(paramsStr,charset);// 构造请求数据
         myEntity.setContentType("application/json");
         post.setEntity(myEntity);// 设置请求体
         String responseContent = null; // 响应内容
         CloseableHttpResponse response = null;
         try {
             response = client.execute(post);
             if (response.getStatusLine().getStatusCode() == 200) {
                 HttpEntity entity = response.getEntity();
                 responseContent = EntityUtils.toString(entity, charset);
             }
         } catch (ClientProtocolException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             try {
                 if (response != null)
                     response.close();
             } catch (IOException e) {
                 e.printStackTrace();
             } finally {
                 try {
                     if (client != null)
                         client.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
         
         return responseContent; 
    }
    
    public static String post(String postUrl,String charset,JSONObject json) {
		return postBusiBody(postUrl,10000,10000,charset,json);
    	
    }
    
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值