欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java

程序员文章站 2024-02-01 20:16:10
...
package com.Annual.Httpclient;


import java.io.File;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;

public class HttpHelper {

//请求读取超时
private Integer socketTimeout = 6000;
//URL的连接等待超时时间
private Integer connectTimeout = 5000;
//连接池获取连接的超时时间
private Integer connectionRequestTimeout = 1000;

    private boolean isConnManager = false;
   
    /**
     * 默认不使用连接池
     */
    public HttpHelper() {
   
}
   
    /**
     * 使用连接池
     *
     * /**
* @since
* PoolingHttpClientConnectionManager
* @since
* maxTotalPool = 200 ;
* maxConPerRoute = 80;
* @since
* Connection
* @since
* socketTimeout = 5000;
* connectionRequestTimeout = 1000;
* connectTimeout = 2000;
     * @param isConnManager true
     */
    public HttpHelper(boolean isConnManager) {
    this.isConnManager = isConnManager;
}
   
    /**
     * 自定义链接对象时间
     * @param socketTimeout 请求读取超时
     * @param connectTimeout URL的连接等待超时时间
     * @param connectionRequestTimeout 连接池获取连接的超时时间
     * @param isConnManager 是否启用连接池管理
     */
    public HttpHelper(Integer socketTimeout,Integer connectTimeout,Integer connectionRequestTimeout,boolean isConnManager) {
    this.socketTimeout = socketTimeout;
    this.connectTimeout = connectTimeout;
    this.connectionRequestTimeout = connectionRequestTimeout;
    this.isConnManager = isConnManager;
}

    /**
     * 使用Get方式 根据URL地址,获取ResponseContent对象
     *
     * @param url完整的URL地址
     * @return ResponseContent 如果发生异常则返回null,否则返回ResponseContent对象
     */
    public ResponseContent getUrlRespContent(String url) {
        HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout,isConnManager);
        ResponseContent response = null;
        try {
            response = hw.getResponse(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 使用Get方式 根据URL地址,获取ResponseContent对象
     *
     * @param url 完整的URL地址
     * @param urlEncoding
     * @return ResponseContent 如果发生异常则返回null,否则返回ResponseContent对象
     */
    public ResponseContent getUrlRespContent(String url, String urlEncoding) {
        HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout,isConnManager);
        ResponseContent response = null;
        try {
            response = hw.getResponse(url, urlEncoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 将参数拼装在url中,进行post请求。
     *
     * @param url 如果有参数直接在拼接在url后面即可
     * @return
     */
    public ResponseContent postUrl(String url) {
    HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout,isConnManager);
        ResponseContent ret = null;
        try {
            setParams(url, hw);
            ret = hw.postNV(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
   
    /**
     * 将参数进行post请求。
     *
     * @param url 如果有参数直接在拼接在url后面即可
     * @return
     */
    public ResponseContent post(String url,Map paramsMap) {
    HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout,isConnManager);
        ResponseContent ret = null;
        try {
            Iterator iterator = paramsMap.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value = paramsMap.get(key);
                if (value != null && !"".equals(value)) {
                    hw.addNV(key, String.valueOf(value));
                } else {
                    hw.addNV(key, "");
                }
            }
            ret = hw.postNV(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
   
    /**
     * 上传文件(包括图片)
     *
     * @param url 请求URL
     * @param paramsMap 参数和值
     * @return
     */
    public ResponseContent postEntity(String url, Map paramsMap) {
    HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout,isConnManager);
        ResponseContent ret = null;
        try {
            setParams(url, hw);
            Iterator iterator = paramsMap.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value = paramsMap.get(key);
                if (value instanceof File) {
                    FileBody fileBody = new FileBody((File) value);
                    hw.getContentBodies().add(fileBody);
                } else if (value instanceof byte[]) {
                    byte[] byteVlue = (byte[]) value;
                    ByteArrayBody byteArrayBody = new ByteArrayBody(byteVlue, key);
                    hw.getContentBodies().add(byteArrayBody);
                } else {
                    if (value != null && !"".equals(value)) {
                        hw.addNV(key, String.valueOf(value));
                    } else {
                        hw.addNV(key, "");
                    }
                }
            }
            ret = hw.postEntity(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    private static void setParams(String url, HttpClientWrapper hw) {
        String[] paramStr = url.split("[?]", 2);
        if (paramStr == null || paramStr.length != 2) {
            return;
        }
        String[] paramArray = paramStr[1].split("[&]");
        if (paramArray == null) {
            return;
        }
        for (String param : paramArray) {
            if (param == null || "".equals(param.trim())) {
                continue;
            }
            String[] keyValue = param.split("[=]", 2);
            if (keyValue == null || keyValue.length != 2) {
                continue;
            }
            hw.addNV(keyValue[0], keyValue[1]);
        }
    }

   

    /**
     * 使用post方式,发布对象转成的json给Rest服务。
     *
     * @param url
     * @param jsonBody
     * @return
     */
    public ResponseContent postJsonEntity(String url, String jsonBody) {
        return postEntity(url, jsonBody, "application/json");
    }

    /**
     * 使用post方式,发布对象转成的xml给Rest服务
     *
     * @param url URL地址
     * @param xmlBody xml文本字符串
     * @return ResponseContent 如果发生异常则返回空,否则返回ResponseContent对象
     */
    public ResponseContent postXmlEntity(String url, String xmlBody) {
        return postEntity(url, xmlBody, "application/xml");
    }

    private ResponseContent postEntity(String url, String body, String contentType) {
    HttpClientWrapper hw = new HttpClientWrapper(connectionRequestTimeout, connectTimeout, socketTimeout,isConnManager);
        ResponseContent ret = null;
        try {
            hw.addNV("body", body);
            ret = hw.postNV(url, contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}

相关标签: http