httpclient发送GET,POST请求,上传下载文件工具类
原创    bellys    发表于:2017-07-11 18:15:09
  阅读 :778   收藏   编辑
maven依赖:
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.3.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.3.5</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

测试:

public static void main(String[] args) throws ParseException, IOException {
        String url = "http://www.faceghost.com/";
        HttpResponseUtils utils =  HttpRequestUtils.doGet(url, null, "UTF-8");
        System.out.println(utils);

    }
请求工具类:
public class HttpRequestUtils {

    private static int  totalConn = 1000;

    private static  RequestConfig config;

    static{

        config = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();

    }


    /**
     * 发送Http get 请求
     * @param url 请求URL,
     * @param params 请求参数,eg : ReqParams.init().addParam(name, val)
     * @param charset 编码格式
     * @return 返回HttpResponseUtils实例
     * @throws ParseException
     * @throws IOException
     */
    public static HttpResponseUtils doGet(String url,ReqParams params,String charset) throws ParseException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpResponseUtils response = HttpResponseUtils.init();
        if(url == null)return null;
        if(params != null){
            url += "?" + EntityUtils.toString(params.getReqParams(charset));
        }
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse httpResponse  = httpClient.execute(get);
        RequestLine requestLine = get.getRequestLine();
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setUri(requestLine.getUri());
        response.setMethod(requestLine.getMethod());
        response.setProtocolVersion(requestLine.getProtocolVersion());
        HttpEntity entity  = httpResponse.getEntity();
        if(entity != null){ 
            response.setHtml(EntityUtils.toString(entity));
            response.setContentEncoding(entity.getContentEncoding()+"");
            response.setContentLength(entity.getContentLength());
            response.setContentType(entity.getContentType().getValue());
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        httpClient.close();
        return response;
    }

    /**
     * 发送Http get 请求
     * @param url 请求URL,
     * @param params 请求参数,eg : ReqParams.init().addParam(name, val)
     * @param config 请求配置,默认:RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();
     * @param charset 编码格式
     * @return 返回HttpResponseUtils实例
     * @throws ParseException
     * @throws IOException
     */
    public static HttpResponseUtils doGet(String url,ReqParams params,RequestConfig config,String charset) throws ParseException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpResponseUtils response = HttpResponseUtils.init();
        if(url == null)return null;
        if(params != null){
            url += "?" + EntityUtils.toString(params.getReqParams(charset));
        }
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse httpResponse  = httpClient.execute(get);
        RequestLine requestLine = get.getRequestLine();
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setUri(requestLine.getUri());
        response.setMethod(requestLine.getMethod());
        response.setProtocolVersion(requestLine.getProtocolVersion());
        HttpEntity entity  = httpResponse.getEntity();
        if(entity != null){ 
            response.setHtml(EntityUtils.toString(entity));
            response.setContentEncoding(entity.getContentEncoding()+"");
            response.setContentLength(entity.getContentLength());
            response.setContentType(entity.getContentType().getValue());
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        httpClient.close();
        return response;
    }


    /**
     * 发送Http Post 请求
     * @param url 请求URL,
     * @param params 请求参数,eg : ReqParams.init().addParam(name, val)
     * @param charset 编码格式
     * @return 返回HttpResponseUtils实例
     * @throws ParseException
     * @throws IOException
     */
    public static HttpResponseUtils doPost(String url,ReqParams params,String charset) throws ParseException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpResponseUtils response = HttpResponseUtils.init();
        if(url == null)return null;
        HttpPost post = new HttpPost(url);
        if(params != null) {
            post.setEntity(params.getReqParams(charset));
        }
        CloseableHttpResponse httpResponse  = httpClient.execute(post);
        RequestLine requestLine = post.getRequestLine();
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setUri(requestLine.getUri());
        response.setMethod(requestLine.getMethod());
        response.setProtocolVersion(requestLine.getProtocolVersion());
        HttpEntity entity  = httpResponse.getEntity();
        if(entity != null){ 
            response.setHtml(EntityUtils.toString(entity));
            response.setContentEncoding(entity.getContentEncoding()+"");
            response.setContentLength(entity.getContentLength());
            response.setContentType(entity.getContentType().getValue());
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        httpClient.close();
        return response;
    }

    /**
     * 发送Http Post 请求
     * @param url 请求URL,
     * @param params 请求参数,eg : ReqParams.init().addParam(name, val)
     * @param config 请求配置,默认:RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build();
     * @param charset 编码格式
     * @return 返回HttpResponseUtils实例
     * @throws ParseException
     * @throws IOException
     */
    public static HttpResponseUtils doPost(String url,ReqParams params,RequestConfig config,String charset) throws ParseException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpResponseUtils response = HttpResponseUtils.init();
        if(url == null)return null;
        HttpPost post = new HttpPost(url);
        if(params != null) {
            post.setEntity(params.getReqParams(charset));
        }
        CloseableHttpResponse httpResponse  = httpClient.execute(post);
        RequestLine requestLine = post.getRequestLine();
        response.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        response.setUri(requestLine.getUri());
        response.setMethod(requestLine.getMethod());
        response.setProtocolVersion(requestLine.getProtocolVersion());
        HttpEntity entity  = httpResponse.getEntity();
        if(entity != null){ 
            response.setHtml(EntityUtils.toString(entity));
            response.setContentEncoding(entity.getContentEncoding()+"");
            response.setContentLength(entity.getContentLength());
            response.setContentType(entity.getContentType().getValue());
        }
        EntityUtils.consume(entity);
        httpResponse.close();
        httpClient.close();
        return response;
    }

    /**
     * 通过httpClient get 下载文件
     * @param url 网络文件全路径
     * @param savePath 保存文件全路径
     * @return 状态码 200表示成功
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static int doDownload(String url,String savePath) throws ClientProtocolException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity entity =  response.getEntity();
        if(entity != null){
            InputStream  in = entity.getContent();
            FileOutputStream out = new FileOutputStream(savePath);
            IOUtils.copy(in, out);
            EntityUtils.consume(entity);
            response.close();

        }
        int code = response.getStatusLine().getStatusCode();
        httpClient.close();
        return code;
    }

    /**
     * 通过HttpClint post 上传文件
     * @param url    上传请求地址
     * @param fileBody  文件类型input Map
     * @param stringBody 普通类型input Map
     * @return 状态码 200表示成功
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static int doUpload(String url,Map<String, String> fileBody,Map<String,String> stringBody) throws ClientProtocolException, IOException{
        CloseableHttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(totalConn).setDefaultRequestConfig(config).build();
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if(fileBody != null){
            Iterator<String> fileIter = fileBody.keySet().iterator();
            while (fileIter.hasNext()) {
                String key = (String) fileIter.next();
                String value = fileBody.get(key);
                builder.addPart(key, new FileBody(new File(value)));
            }
        }
        if(stringBody != null){
            Iterator<String> stringIter = stringBody.keySet().iterator();
            while (stringIter.hasNext()) {
                String key = (String) stringIter.next();
                String value = stringBody.get(key);
                builder.addPart(key, new StringBody(value,ContentType.TEXT_PLAIN));        
            }
        }
        post.setEntity(builder.build());
        CloseableHttpResponse response = httpClient.execute(post);
        int code = response.getStatusLine().getStatusCode();
        httpClient.close();
        return code;
    }

}
请求返回工具类:
public class HttpResponseUtils {

    private HttpResponseUtils(){};

    public static  HttpResponseUtils init(){
        return new HttpResponseUtils();
    }

    private String html;

    private int statusCode ;

    private String method;

    private String uri;

    private ProtocolVersion protocolVersion;

    private String contentEncoding;

    private String contentType;

    private long contentLength;

    //get set 

    @Override
    public String toString() {
        return "HttpResponseUtils [contentEncoding=" + contentEncoding
                + ", contentLength=" + contentLength + ", contentType="
                + contentType + ", html=" + html + ", method=" + method
                + ", protocolVersion=" + protocolVersion + ", statusCode="
                + statusCode + ", uri=" + uri + "]";
    }

}
请求参数工具类
/**
 * <pre>
 * 类名称    : requestParams
 * 类描述    : 发送Get或Post请求参数
 * 修改备注:
 * </pre>
 */
public class ReqParams {

    private  Map<String, String> reqParams = new HashMap<String, String>();

    private ReqParams(){}

    /**
     * 初始化  返回this,方便链式操作
     * @return this
     */
    public static ReqParams init(){
        return  new ReqParams();
    }

    /**
     * 添加参数  返回this,方便链式操作
     * @param key
     * @param val
     * @return this
     */
    public ReqParams addParam(String name,String val){
        reqParams.put(name, val);
        return this;
    }

    /**
     * 得到参数 返回Map
     * @return Map
     * @throws UnsupportedEncodingException 
     */
    public UrlEncodedFormEntity getReqParams(String charset){ 
        List<NameValuePair> parms = new ArrayList<NameValuePair>();
        if(reqParams != null){
            Iterator<Entry<String, String>> iter =  reqParams.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
                parms.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            if(parms != null && parms.size()>0){
                try {
                    return new  UrlEncodedFormEntity(parms, charset);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + charset);
                }
            }
        }
        return null;
    }
}
评论
条评论