HttpUtils 发送http请求工具类

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.pingan.qhcs.map.audit.constant.CodeConstant;
import com.pingan.qhcs.map.audit.exception.MapException;

public class HttpClientUtil {

    protected static Log logger = LogFactory.getLog(HttpClientUtil.class);

    private static PoolingHttpClientConnectionManager cm;
    private static String EMPTY_STR = "";
    private static String UTF_8 = "UTF-8";

    private static void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
        }
    }

    /**
     * 通过连接池获取HttpClient
     *
     * @return
     */
    public static CloseableHttpClient getHttpClient() {
        init();
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String httpGetRequest(String url) {
        HttpGet httpGet = new HttpGet(url);
        return getResult(httpGet);
    }

    public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());

        return getResult(httpGet);
    }

    public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        ub.setParameters(pairs);

        HttpGet httpGet = new HttpGet(ub.build());
        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        return getResult(httpGet);
    }

    public static String httpPostRequest(String url) {
        HttpPost httpPost = new HttpPost(url);
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
            throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }

        ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));

        return getResult(httpPost);
    }

    public static String httpPostRequest(String url, Map<String, Object> headers, String strBody)
            throws Exception {
        HttpPost httpPost = new HttpPost(url);

        for (Map.Entry<String, Object> param : headers.entrySet()) {
            httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
        }
        httpPost.setEntity(new StringEntity(strBody, UTF_8));
        return getResult(httpPost);
    }

    private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }

        return pairs;
    }

    /**
     * 处理Http请求
     *
     *  setConnectTimeout:设置连接超时时间,单位毫秒。
     *  setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
     *  setSocketTimeout:请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
     *
     * @param request
     * @return
     */
    private static String getResult(HttpRequestBase request) {

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(5000).setSocketTimeout(60000).build();
        request.setConfig(requestConfig);// 设置请求和传输超时时间

        // CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = getHttpClient();
        try {
            CloseableHttpResponse response = httpClient.execute(request); //执行请求
            // response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // long len = entity.getContentLength();// -1 表示长度未知
                String result = EntityUtils.toString(entity);
                response.close();
                // httpClient.close();
                return result;
            }
        } catch (ClientProtocolException e) {
            logger.error("[maperror] HttpClientUtil ClientProtocolException : " + e.getMessage());
            throw new MapException(CodeConstant.CODE_CONNECT_FAIL, "HttpClientUtil ClientProtocolException :" + e.getMessage());
        } catch (IOException e) {
            logger.error("[maperror] HttpClientUtil IOException : " + e.getMessage());
            throw new MapException(CodeConstant.CODE_CONNECT_FAIL, "HttpClientUtil IOException :" + e.getMessage());
        } finally {

        }
        return EMPTY_STR;
    }

}
时间: 2024-10-11 20:59:52

HttpUtils 发送http请求工具类的相关文章

java jdk原生的http请求工具类

package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net

iOS_21团购_通过block对请求工具类的代理方法进行二次封装

最终效果图: [点评]提供的工具类DPAPI 在请求完毕后,使用的是代理机制,当一次请求成功或者失败时,会调用代理的相应方法 为了将点评提供的工具类DPAPI进行二次封装, 再次定义了一个block: typedef  void(^RequestDoneCallBackBlock)(id deals,NSError *err); 该block有两个参数, 分别是成功时,服务器返回的deals字典数组 另一个参数是:请求失败时,服务器返回的失败信息 两个参数分别对应代理的两个方法(即成功.失败时分

我的Android进阶之旅------&gt;Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEn

发送广播简易工具类

/** * 发送广播简易工具类 * Created by Liam on 2015/4/2. */ public class BroadcastUtil { /** * 构造函数设为private,防止外部实例化 */ private void BroadcastManager() { } /** * 注册广播接收器 * * @param ctx Context(不可空) * @param iReceiver IReceiver(不可空) * @param action Intent.Actio

发送请求工具类

采用HttpClient与远程服务器通信,所以定义一个工具类对HttpClient进行封装getRequest():发送get请求postRequest():发送post请求 FutureTask(Callable<V> callable)  //创建一个 FutureTask,一旦运行就执行给定的 Callable. FutureTask(Runnable runnable, V result)   //创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时

Java http请求工具类

该工具类可以调用POST请求或者Get请求,参数以Map的方式传入,支持获获取返回值,返回值接收类型为String HttpRequestUtil.java package com.util; import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.List;import java.ut

HttpUtils.java 网络下载工具类

package Http; import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL; /** * 网络下载工具类 * 功能:下载字节数组,下载文本数据 * 下载数字数组(文本 图片 mp3) * 下载文本数据 * Created by lxj-pc on 2017/

网络请求工具类WebServiceUtils

如果对WebService一无所知的话,建议先看看这两篇博客,对你WebService很有帮助. http://blog.csdn.NET/eyu8874521/article/details/9125987 http://blog.csdn.net/xiaanming/article/details/16871117 本人也是菜鸟一名,WebService已经是很老的技术了,但现在仍有使用,刚开始接触的时候,是无从入手呀,看了上面几篇文章以后,渐渐的会使用了,这里感谢网上开源的作者和文章,网上

Java HttpClient4.2.x版本get、post请求工具类

公司业务需要,跟很多公司合作,经常需要请求外部http接口,而项目架构是一个比较老的框架整合,仅http请求的工具类就很多个,显得杂乱无章: 有些接口测试时,对方做了IP白名单限制的,ZIP压缩等要求,现有的http工具类无法满足要求,又不能去修改,因为很多地方在用:想引入最新HttpClient版本的依赖,确发现与现有的jar包冲突: 无耐只能使用现有的jar重新封装,具体代码演示如下: post请求方式1 /*** POST请求,超时时间必须设置* @param url* @param js