HttpClient4.5

常用的HttpClient类4.5配置

所用的jar包有

httpclient-4.5.1.jar

httpcore-4.4.3.jar

httpmime-4.5.1.jar

还有个工具类jar包

commons-io-2.4.jar

下载地址:http://download.csdn.net/detail/u011348453/9392605

HttpHelper

package com.xvli.utils;

import com.xvli.comm.HttpConfig;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.CookieSpecs;
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.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

/**
 * HttpClient帮助类
 */
public class HttpHelper {
    private static HttpHelper xmlHttpHelper;
    private CloseableHttpClient httpClient;
    private RequestConfig requestConfig;

    private HttpHelper() {
    }

    public static HttpHelper getInstance() {
        if (xmlHttpHelper == null) {
            xmlHttpHelper = new HttpHelper();
        }
        return xmlHttpHelper;
    }

    /**
     * GET方法
     *
     * @param url
     * @param params
     * @return
     */
    public String doGet(String url, HashMap<String, String> params) {
        httpClient = getHttpClient();
        String content = "";
        CloseableHttpResponse response = null;
        if (params != null && params.size() > 0) {
            NetParams netParams = new NetParams();
            Iterator<Entry<String, String>> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry<String, String> item = iter.next();
                String key = item.getKey();
                String value = item.getValue();
                netParams.addParam(key, value);
            }
            if (url.contains("?")) {
                url = url + netParams.getParamsAsString();
            } else {
                url = url + "?" + netParams.getParamsAsString();
            }
        }
        HttpGet httpGet = new HttpGet(url);

        System.out.println("url-->" + url + "\ndata-->" + params.toString());
        try {
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine().getStatusCode() + "");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    long len = entity.getContentLength();
                    if (len != -1 && len < 2048) {
                        content = EntityUtils.toString(entity, Consts.UTF_8);
                    } else {
                        content = IOUtils.toString(entity.getContent(), Consts.UTF_8);
                    }
                }
                EntityUtils.consume(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    /**
     * POST方法
     *
     * @param url
     * @param params
     * @return
     */
    public String doPost(String url, HashMap<String, String> params) {
        httpClient = getHttpClient();
        String content = "";
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);
        if (params != null && params.size() > 0) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry<String, String> item = iter.next();
                String key = item.getKey();
                String value = item.getValue();
                formparams.add(new BasicNameValuePair(key, value));
            }
            System.out.println("url-->" + url + "\ndata-->" + params.toString());
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            httpPost.setEntity(urlEncodedFormEntity);// 上传参数在这里
        }
        try {
            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode() + "");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    long len = entity.getContentLength();
//                    if (len != -1 && len < 2048) {
                        content = EntityUtils.toString(entity, Consts.UTF_8);
                   /* } else {
                        content = IOUtils.toString(entity.getContent(), Consts.UTF_8);
                    }*/
                }
                EntityUtils.consume(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content.toString();
    }

    /**
     * 下载文件并保存GET方式
     *
     * @param url
     * @param params
     * @param targetFile
     */
    public void downLoadSaveFileGET(String url, HashMap<String, String> params, File targetFile) {
        CreateFileIfNotExtends(targetFile);
        httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        if (params != null && params.size() > 0) {
            NetParams netParams = new NetParams();
            Iterator<Entry<String, String>> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry<String, String> item = iter.next();
                String key = item.getKey();
                String value = item.getValue();
                netParams.addParam(key, value);
            }
            if (url.contains("?")) {
                url = url + netParams.getParamsAsString();
            } else {
                url = url + "?" + netParams.getParamsAsString();
            }
        }
        HttpGet httpGet = new HttpGet(url);
        System.out.println("url-->" + url + "\ndata-->" + params.toString());

        try {
            response = httpClient.execute(httpGet);
            System.out.println(response.getStatusLine().getStatusCode() + "");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    OutputStream outputStream = new FileOutputStream(targetFile);
                    InputStream inputStream = entity.getContent();
                    IOUtils.copy(inputStream, outputStream);
                    outputStream.close();
                }
                EntityUtils.consume(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载文件并保存POST方式(有些服务器并不支持405) 【You are doing a POST but for some reason IIS
     * does not allow POST for whatever resource you are accessing (maybe a WCF
     * .svc extension?). Seems the "StaticFileModule" is the one complaining
     * based on the error page you get back.】
     *
     * @param url
     * @param params
     * @param targetFile
     */
    public void downLoadSaveFilePOST(String url, HashMap<String, String> params, File targetFile) {
        CreateFileIfNotExtends(targetFile);
        httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        if (params != null && params.size() > 0) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry<String, String> item = iter.next();
                String key = item.getKey();
                String value = item.getValue();
                formparams.add(new BasicNameValuePair(key, value));
            }
            System.out.println("url-->" + url + "\ndata-->" + params.toString());
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            httpPost.setEntity(urlEncodedFormEntity);// 上传参数在这里
        }
        try {
            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode() + "");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    OutputStream outputStream = new FileOutputStream(targetFile);
                    InputStream inputStream = entity.getContent();
                    IOUtils.copy(inputStream, outputStream);
                    outputStream.close();
                }
                EntityUtils.consume(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件和一些参数
     *
     * @param url
     * @param params
     * @param files
     * @return
     */
    public String upLoadFilePOST(String url, HashMap<String, String> params, HashMap<String, Object> files) {
        httpClient = getHttpClient();
        String content = "";
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        if ((files != null && files.size() > 0) || (params != null && params.size() > 0)) {
            MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
            multipartBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartBuilder.setCharset(Consts.UTF_8);
            Iterator<Entry<String, Object>> fileIter = files.entrySet().iterator();// 遍历HashMap
            while (fileIter.hasNext()) {
                Entry<String, Object> item = fileIter.next();
                String fileKey = item.getKey();
                File valueFile = (File) item.getValue();
                String fileName = FilenameUtils.getName(valueFile.getAbsolutePath());//文件名称aaa.jpg
                String extension = FilenameUtils.getExtension(valueFile.getAbsolutePath());// 文件后缀名jpg
                if (extension.equals("zip") || extension.equals("rar")) {
                    try {
                        InputStream inputStream = FileUtils.openInputStream(valueFile);//就是读出流
                        multipartBuilder.addBinaryBody(fileKey, inputStream, ContentType.create("application/x-zip-compressed"), fileName);
                        inputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    multipartBuilder.addBinaryBody(fileKey, valueFile, ContentType.DEFAULT_BINARY, fileName);
                }
            }
            if (params != null && params.size() > 0) {
                Iterator<Entry<String, String>> iter = params.entrySet().iterator();// 遍历HashMap
                while (iter.hasNext()) {
                    Entry<String, String> item = iter.next();
                    String key = item.getKey();
                    String value = item.getValue();
                    multipartBuilder.addTextBody(key, value, ContentType.create("text/plain", Consts.UTF_8));
                }
            }
            System.out.println("url-->" + url + "\ndata-params->" + params.toString() + "\ndata-params->" + files.size());
            HttpEntity entity = multipartBuilder.build();
            httpPost.setEntity(entity);
        }
        try {
            response = httpClient.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode() + "");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    long len = entity.getContentLength();
                    if (len != -1 && len < 2048) {
                        content = EntityUtils.toString(entity, Consts.UTF_8);
                    } else {
                        content = IOUtils.toString(entity.getContent(), Consts.UTF_8);
                    }
                }
                EntityUtils.consume(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return content;
    }

    /**
     * 定义好自己的HttpClient,超时设置都在这里设置
     *
     * @return httpClient
     */
    private CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = null;
        if (HttpConfig.SET_PROXY) {// 如果需要代理,就在这里插入代理
            HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
            requestConfig = RequestConfig.custom().setProxy(proxy).setConnectTimeout(HttpConfig.CONNECT_TIMEOUT).setSocketTimeout(60000).setConnectionRequestTimeout(60000)
                    .setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        } else {
            requestConfig = RequestConfig.custom().setConnectTimeout(HttpConfig.CONNECT_TIMEOUT).setSocketTimeout(60000).setConnectionRequestTimeout(60000)
                    .setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
        }
        if (HttpConfig.SET_DEFAULT_REDIRECT) {
            if (HttpConfig.SET_DEFAULT_HEADER) {
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setRedirectStrategy(new LaxRedirectStrategy()).setDefaultHeaders(setDefaultHeaders())
                        .build();
            } else {
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setRedirectStrategy(new LaxRedirectStrategy()).build();
            }
        } else {
            if (HttpConfig.SET_DEFAULT_HEADER) {
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setDefaultHeaders(setDefaultHeaders()).build();
            } else {
                httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            }
        }
        return httpClient;

    }

    /**
     * 设置默认的Header
     *
     * @return
     */
    private List<Header> setDefaultHeaders() {
        List<Header> headers = new ArrayList<Header>();
        Header header1 = new BasicHeader("imei", "Imei12345");
        Header header2 = new BasicHeader("pdatype", "1");
        headers.add(header1);
        headers.add(header2);

        return headers;
    }

    /**
     * 如果文件不存在就创建文件
     *
     * @param file
     */
    private void CreateFileIfNotExtends(File file) {
        // 如果文件夹不存在则创建
        if (!file.exists()) {
            System.out.println("文件不存在");
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件存在");
        }
    }

    /**
     * 直接把类放到这里了
     *
     * @author MrFu
     */
    private class NetParams {

        int paramsNumbers = 0;
        private StringBuffer result = new StringBuffer();

        public NetParams() {
        }

        /**
         * 添加一个参数,参数无须编码
         */
        public void addParam(String key, String value) {
            if (paramsNumbers != 0) {
                result.append("&");
            }
            try {
                result.append(key + "=" + URLEncoder.encode(value, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            paramsNumbers++;
        }
        public String getParamsAsString() {
            return result.toString();
        }
    }

}

HttpConfig

package com.xvli.comm;

public class HttpConfig {

    /**
     * 设置代理否
     */
    public static final boolean SET_PROXY = false;//暂时不需要代理
    /**
     * 是否设置默认Header
     */
    public static final boolean SET_DEFAULT_HEADER = false;
    /**
     * 是否重定向
     */
    public static final boolean SET_DEFAULT_REDIRECT = false;
    /**
     * 连接超时时间
     */
    public static final int CONNECT_TIMEOUT = 60000;
    /**
     * 是否打印cookie
     */
    public static final boolean OUTPUT_COOKIE = false;

}
时间: 2024-10-03 20:32:12

HttpClient4.5的相关文章

HttpClient-4.3.X 中get和post方法使用

转自:http://linhongyu.blog.51cto.com/6373370/1538672 一.简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议. HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient. HttpClient这货跟Luenc

httpclient4.3简单封装

对httpclient4.3版本的一个简单封装,下面是代码 /**  * httputil工具类  *   * @author rex  */ public class HttpUtil {     private static CloseableHttpClient client;     private static BasicCookieStore cookieStore;     private static HttpGet get;     private static HttpPos

httpclient4 中文版帮助文档

httpclient4 中文版帮助文档

Atitit 类库冲突解决方案 &#160;httpclient-4.5.2.jar

Atitit 类库冲突解决方案  httpclient-4.5.2.jar 错误提示如下1 版本如下(client and selenium)2 解决流程2 挂载源码 (SSLConnectionSocketFactory.java:1442 原因:SSLConnectionSocketFactory调取AllowAllHostnameVerifier 的时候,调取了另外一个jar里面的allowAhnVer这个class3 解决: 把4.5jar放在前面运行,让它先加载..或者使用代码预先加载

httpclient4.3.x模拟post及get请求

在web开发中,我们经常需要模拟post及get请求,现在网上比较多的是使用httpclient3.x,然而httpclient4.x已经发布好几年了,而且4.x之后改名为HttpComponents,显然是今后的趋势.Apache HttpComponents4.x中的HttpClient是一个很好的工具,它符合HTTP1.1规范,是基于HttpCore类包的实现.但是HttpComponents4.x较之前httpclient3.x的API变化比较大,已经分为HttpClient,HttpC

httpclient4.3 工具类

httpclient4.3  java工具类....因项目需要开发了一个工具类,正常常用的httpclient 请求操作应该都够用了 工具类下载地址:http://download.csdn.net/detail/ruishenh/7421641 package com.ruishenh.utils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntax

apache httpclient-4.5 https通讯 双向认证

maven dependence <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> 2. 测试类 package com.iraid.test; import java.io.BufferedRea

httpclient4.3 导致线程阻塞

项目使用httpclient4.3.3,突然有天发现推送线程池排队,通过jstack 定位到httpclient进行ssl连接时发生阻塞.httpclient 的SocketTimeout 和 ConnectTimeout都有设置. 后分析查找,确认是httpclient4.3.3的bug, 见 https://issues.apache.org/jira/browse/HTTPCLIENT-1478 大概原因是由于ssl握手失败,导致设置的超时时间无效.进而引发现场阻塞,导致线程池线程被占满

学习脚步--- HttpClient4.0, multipartEntity (转)

学习脚步--- HttpClient4.0 Apache网络协议网络应用应用服务器HTML HttpClient程序包是一个实现了 HTTP 协议的客户端编程工具包,要想熟练的掌握它,必须熟悉 HTTP协议.一个最简单的调用如下: Java代码 HttpClient4.0, multipartEntity (转)"> HttpClient4.0, multipartEntity (转)"> import java.io.IOException; import org.apa

【HttpClient4.5中文教程】【第一章 :基础】1.1执行请求(三)

更多HttpClient4.5中文教程请查看:点击打开链接=============================================== 1.1.7.生产实体内容 HttpClient提供了几个类,用来通过HTTP连接高效地传输内容.这些类的实例均与内含实体请求有关,比如POST和PUT,它们能够把实体内容封装进友好的HTTP请求中.对于基本的数据容器String, byte array, input stream, and file,HttpClient为它们提供了几个对应的类