HttpClient4.5

原文链接: http://www.cnblogs.com/bxfx111/p/5105345.html

常用的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 params) {
        httpClient = getHttpClient();
        String content = "";
        CloseableHttpResponse response = null;
        if (params != null && params.size() > 0) {
            NetParams netParams = new NetParams();
            Iterator> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry 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 params) {
        httpClient = getHttpClient();
        String content = "";
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);
        if (params != null && params.size() > 0) {
            List formparams = new ArrayList();
            Iterator> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry 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 params, File targetFile) {
        CreateFileIfNotExtends(targetFile);
        httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        if (params != null && params.size() > 0) {
            NetParams netParams = new NetParams();
            Iterator> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry 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 params, File targetFile) {
        CreateFileIfNotExtends(targetFile);
        httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        HttpPost httpPost = new HttpPost(url);

        if (params != null && params.size() > 0) {
            List formparams = new ArrayList();
            Iterator> iter = params.entrySet().iterator();// 遍历HashMap
            while (iter.hasNext()) {
                Entry 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 params, HashMap 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> fileIter = files.entrySet().iterator();// 遍历HashMap
            while (fileIter.hasNext()) {
                Entry 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> iter = params.entrySet().iterator();// 遍历HashMap
                while (iter.hasNext()) {
                    Entry 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
setDefaultHeaders() { List
headers = new ArrayList
(); 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;

}

 

转载于:https://www.cnblogs.com/bxfx111/p/5105345.html

你可能感兴趣的:(HttpClient4.5)