HttpClient 学习 整理工具类

                                   HttpClient 学习  整理工具类

1.引入架包

     <!-- Apache httpclient IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

2.创建HttpClientUtil 工具类

package com.hxl.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.entity.ContentType;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient 工具类
 * Created by hxl on 2019/8/16.
 */
public class HttpClientUtil {


    /**
     * 设置 超时时间和连接时长
     * .setConnectTimeout()   设置  连接超时时间 单位秒
     * .setSocketTimeout()    设置 请求数据的超时时间 单位秒
     * .setConnectionRequestTimeout() 设置从connect Manager获取Connection 超时时间 单位秒。新加属性 目前版本可以共享连接池
     */
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
            .setConnectionRequestTimeout(15000).build();

    private static HttpClientUtil instance = null;

    /**
     * 单例模式
     */
    private HttpClientUtil() {

    }

    public static HttpClientUtil getInstance() {
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }


    /**
     *
     * @param url 请求地址
     * @param map  参数map
     * @param headerMap 请求头 map
     * @return
     */
    public String sendHttpPost(String url, Map<String, Object> map,Map<String,String> headerMap) {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        String msg = "";
        try {
            // 创建客户端
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);

            // 构造list集合,往里面丢数据 参数构建
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 1.遍历map,设置参数到list中
            if(map != null){
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
                }
            }

            // 我们发现Entity是一个接口,所以只能找实现类,发现实现类又需要一个集合,集合的泛型是NameValuePair类型
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params);
            formEntity.setContentType("Content-Type:application/json");
            httpPost.setEntity(formEntity);

            //2.设置请求头
            if(headerMap != null){
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            // HttpEntity是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            msg = EntityUtils.toString(entity, "UTF-8");
            System.out.println(msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return msg;
    }

    /**
     * get 请求
     *
     * @param url
     * @return
     */
    public String sendHttpGet(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }
        String msg = "";
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            get.setConfig(requestConfig);
            response = httpclient.execute(get);
            msg = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return msg;
    }


    /**
     * MultipartFile 类型 上传
     * @param url  上传接口地址
     * @param file 上传的文件
     * @return 响应结果
     */
    public String httpClientUploadFile(String url,MultipartFile file) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String msg = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交,对应input的name和value
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                msg = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return msg;
    }


    /**
     * 文件下载
     * @param url 请求地址         列:http://www.xxx.com/img/333.jpg
     * @param destFileName 保存地址
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static void getFile(String url, String destFileName)
            throws ClientProtocolException, IOException {
        // 生成一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        File file = new File(destFileName);
        try {
            FileOutputStream fout = new FileOutputStream(file);
            int l = -1;
            byte[] tmp = new byte[1024];
            while ((l = in.read(tmp)) != -1) {
                fout.write(tmp, 0, l);
            }
            fout.flush();
            fout.close();
        } finally {
            // 关闭低层流。
            in.close();
        }
        httpclient.close();
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值