java使用HttpClient发送数据的几种情况

1.发送Http 携带 json格式的数据

import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashMap;

public class HttpClienUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClienUtil.class);

    public static String sandHttpClien(String jsonDataStr,String url){

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // 请求的 地址
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
            // 设置 post 请求参数 json 字符串 形式的
            //String jsonDataStr = JSON.toJSONString(deviceRegisterVO);
            // 修复 POST json 导致中文乱码
            HttpEntity entity = new StringEntity(jsonDataStr,"UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-type", "application/json");
            //发送 请求
            HttpResponse resp = closeableHttpClient.execute(post);
            InputStream respIs = resp.getEntity().getContent();
            byte[] respBytes = IOUtils.toByteArray(respIs);

            // 接受 并转换 回调的数据
            result = new String(respBytes, Charset.forName("UTF-8"));
            //DeviceRegistVO deviceRegistVO = JSON.parseObject(result, DeviceRegistVO.class);
        } catch (Exception e) {
            logger.error("HttpClienUtil post报错", e);
        } finally {
            return result;
        }
    }


}

2.发送Http 携带 表单 格式 带 token 的数据

import com.ruoyi.common.utils.uuid.IdUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class HttpClienUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClienUtil.class);

    private static final Logger reportLogger = LoggerFactory.getLogger("report-info");

    // 登录 接口
    public static String sandHttpClien(Map<String,String> mapData, String url,String token){

//        reportLogger.info("进入sandHttpClien方法");
//        reportLogger.info("参数mapData:" + mapData);
//        reportLogger.info("参数url:" + url);
//        reportLogger.info("参数token:" + token);

        String boundary = IdUtils.simpleUUID();

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // 请求的 地址
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
            // 设置 post 请求参数 json 字符串 形式的
            //String jsonDataStr = JSON.toJSONString(deviceRegisterVO);
            // 修复 POST json 导致中文乱码
//            HttpEntity entity = new StringEntity(jsonDataStr,"UTF-8");
//            post.setEntity(entity);
//            post.setHeader("Content-type", "application/json");



            post.addHeader("Content-type", "multipart/form-data; charset=UTF-8; boundary=" + boundary);
            post.addHeader("Accept", "*/*");
            post.addHeader("Accept-Encoding", "UTF-8");
            post.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36");
            if(token != null){
                post.addHeader("Authorization", "Bearer " + token);
            }

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8).setBoundary(boundary);

            ContentType contentType = ContentType.create("text/plain",Charset.forName("UTF-8"));

            Set keySet = mapData.keySet();

            for (Object key : keySet) {
                // 设置请求参数
                multipartEntityBuilder.addTextBody(key.toString(), mapData.get(key),contentType);
            }


            HttpEntity postFormDataBody = multipartEntityBuilder.build();

            // 请求参数
            post.setEntity(postFormDataBody);
            //发送 请求
//            reportLogger.info("sandHttpClien方法 发送请求前 ");
            HttpResponse resp = closeableHttpClient.execute(post);
//            reportLogger.info("sandHttpClien方法 发送请求后 ");
            InputStream respIs = resp.getEntity().getContent();
            byte[] respBytes = IOUtils.toByteArray(respIs);

            // 接受 并转换 回调的数据
            result = new String(respBytes, Charset.forName("UTF-8"));
            //DeviceRegistVO deviceRegistVO = JSON.parseObject(result, DeviceRegistVO.class);
        } catch (Exception e) {
            logger.error("HttpClienUtil post报错", e);
            reportLogger.error("HttpClienUtil post报错", e);
        } finally {
            reportLogger.info("sandHttpClien方法 收到的返回结果: " +result );
            return result;
        }
    }


}

3.发送 Http 通过绑定 代理IP和端口的 数据

import org.apache.commons.compress.utils.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class HttpUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClienUtil.class);

    public static String sandHttpClien(String jsonDataStr,String url){

       // HttpHost proxy = new HttpHost("192.168.110.253",60601);


        String result = "";
        // 代理服务器信息
        HttpHost proxy = new HttpHost("192.168.110.253",60601);

        // 创建连接管理器并设置代理
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        // 创建HttpClient并设置连接管理器和路由规划器
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connManager)
                .setRoutePlanner(routePlanner)
                .build()) {
            // 创建HTTP GET请求
            HttpPost request = new HttpPost(url);
            HttpEntity entity = new StringEntity(jsonDataStr,"UTF-8");
            request.setEntity(entity);
            request.setHeader("Content-type", "application/json");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(request)) {

                InputStream respIs = response.getEntity().getContent();
                byte[] respBytes = IOUtils.toByteArray(respIs);

                // 接受 并转换 回调的数据
                result = new String(respBytes, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return result;
        }


    }
}

3.发送 Https 带 p12 证书的 数据

import com.ruoyi.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpsUtil {

    private Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
    /**客户端证书路径*/
    private static final ClassPathResource KEY_STORE_CLIENT_PATH = new ClassPathResource("ca/client.p12");
    /** keystore类型JKS*/
    private static final String KEY_STORE_TYPE_JKS = "JKS";
    /** keystore密码*/
    private static final String KEYSTORE_PASSWORD = "123456";
    private CloseableHttpClient httpClient;
    /**
     * @throws Exception
     */
    public HttpsUtil()  {
        try {
            KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_JKS);
            KeyStore trustKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream instream = KEY_STORE_CLIENT_PATH.getInputStream();

            try {
                //密钥库口令
                keyStore.load(instream, KEYSTORE_PASSWORD.toCharArray());
            } catch (CertificateException e) {
                logger.error("加载客户端端可信任证书出错了", e);
            } finally {
                try {
                    instream.close();
                } catch (Exception ignore) {
                }
            }
            SSLContext sslcontext = SSLContexts.custom()
                    //忽略掉对服务器端证书的校验
                    .loadTrustMaterial(new TrustStrategy() {
                        @Override
                        public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                            return true;
                        }

                    })
                    .loadKeyMaterial(keyStore, KEYSTORE_PASSWORD.toCharArray())
                    .build();

            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[]{"TLSv1.1"},
                    null,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            this.httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslConnectionSocketFactory)
                    .build();
        } catch (KeyStoreException e) {
            logger.error("HttpsUtil初始化报错", e);
        } catch (IOException e) {
            logger.error("HttpsUtil初始化报错", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("HttpsUtil初始化报错", e);
        } catch (KeyManagementException e) {
            logger.error("HttpsUtil初始化报错", e);
        } catch (UnrecoverableKeyException e) {
            logger.error("HttpsUtil初始化报错", e);
        }
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param map
     * @throws Exception
     */
    public String post(String url, Map<String, Object> map) throws Exception {
        // 声明POST请求
        HttpPost httpPost = new HttpPost(url);
        // 判断map不为空
        if (null != map) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            formEntity.setContentType("Content-Type:application/json");
            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }
        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        // 获取实体
        HttpEntity entity = response.getEntity();
        // 将实体装成字符串
        String res = EntityUtils.toString(entity, Charset.defaultCharset());
        EntityUtils.consume(entity);
        return res;
    }

    /**
     * 发送POST请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public String get(String url, Map<String, Object> map) throws Exception {

        String params = null;
        if (null != map) {
            // 声明存放参数的List集合
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 转化参数
            params = EntityUtils.toString(new UrlEncodedFormEntity(list, "utf-8"));
        }
        url += StringUtils.isNotBlank(params) ? ("?" + params) : "";
        HttpGet httpGet = new HttpGet(url);
        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        // 获取实体
        HttpEntity entity = response.getEntity();
        // 将实体装成字符串
        String res = EntityUtils.toString(entity, Charset.defaultCharset());
        EntityUtils.consume(entity);
        response.close();
        return res;
    }

    /**
     * 发送POST请求(JSON参数)
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public String post(String url, String json) {
        String res = null;
        try {
            // 声明POST请求
            HttpPost httpPost = new HttpPost(url);
            // 表示客户端发送给服务器端的数据格式
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");
            StringEntity param = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(param);
            CloseableHttpResponse resp = this.httpClient.execute(httpPost);
            HttpEntity entity = resp.getEntity();
            // 将实体装成字符串
            res = EntityUtils.toString(entity, Charset.defaultCharset());
            EntityUtils.consume(entity);
            resp.close();
        } catch (UnsupportedCharsetException e) {
            logger.error("HttpsUtil post报错", e);
        } catch (IOException e) {
            logger.error("HttpsUtil post报错", e);
        } catch (ParseException e) {
            logger.error("HttpsUtil post报错", e);
        }
        return res;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

OOObject

你的鼓励是我创作的最大源泉

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值