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() {@Overridepublic 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发起请求,返回responseCloseableHttpResponse 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发起请求,返回responseCloseableHttpResponse 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;}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/62952.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

华为、华三交换机纯Web下如何创关键VLANIF、操作STP参数

华为交换机WEB操作 使用的是真机S5735&#xff0c;目前主流的版本都适用&#xff08;V1R5~V2R1的就不在列了&#xff0c;版本太老了&#xff0c;界面完全不一样&#xff0c;这里调试线接的console口&#xff0c;电脑的网络接在ETH口&#xff09; 「模拟器、工具合集」复制整段内…

详解Java数据库编程之JDBC

目录 首先创建一个Java项目 在Maven中央仓库下载mysql connector的jar包 针对MySQL版本5 针对MySQL版本8 下载之后&#xff0c;在IDEA中创建的项目中建立一个lib目录&#xff0c;然后把刚刚下载好的jar包拷贝进去&#xff0c;然后右键刚刚添加的jar包&#xff0c;点击‘添…

网络(TCP)

目录 TCP socket API 详解 套接字有哪些类型&#xff1f;socket有哪些类型&#xff1f; 图解TCP四次握手断开连接 图解TCP数据报结构以及三次握手&#xff08;非常详细&#xff09; socket缓冲区以及阻塞模式详解 再谈UDP和TCP bind(): 我们的程序中对myaddr参数是这样…

【笔记】离散数学 1-3 章

1. 数理逻辑 1.1 命题逻辑的基本概念 1.1.1 命题的概念 命题&#xff08;Proposition&#xff09;&#xff1a;是一个陈述句&#xff0c;它要么是真的&#xff08;true&#xff09;&#xff0c;要么是假的&#xff08;false&#xff09;&#xff0c;但不能同时为真和假。例如…

【Linux篇】权限管理 - 用户与组权限详解

一. 什么是权限&#xff1f; 首先权限是限制人的。人 真实的人 身份角色 权限 角色 事物属性 二. 认识人–用户 Linux下的用户分为超级用户和普通用户 root :超级管理员&#xff0c;几乎不受权限的约束普通用户 :受权限的约束超级用户的命令提示符是#&#xff0c;普通用…

【机器学习】机器学习的基本分类-监督学习-决策树-C4.5 算法

C4.5 是由 Ross Quinlan 提出的决策树算法&#xff0c;是对 ID3 算法的改进版本。它在 ID3 的基础上&#xff0c;解决了以下问题&#xff1a; 处理连续型数据&#xff1a;支持连续型特征&#xff0c;能够通过划分点将连续特征离散化。处理缺失值&#xff1a;能够在特征值缺失的…

2023年MathorCup高校数学建模挑战赛—大数据竞赛B题电商零售商家需求预测及库存优化问题求解全过程文档及程序

2023年MathorCup高校数学建模挑战赛—大数据竞赛 B题 电商零售商家需求预测及库存优化问题 原题再现&#xff1a; 电商平台存在着上千个商家&#xff0c;他们会将商品货物放在电商配套的仓库&#xff0c;电商平台会对这些货物进行统一管理。通过科学的管理手段和智能决策&…

cocotb pytest

打印python中的print &#xff0c; 应该使用 pytest -s pytest --junitxmltest_report.xml --htmlreport.html

【Linux】进程间关系与守护进程

&#x1f30e;进程间关系与守护进程 文章目录&#xff1a; 进程间关系与守护进程 进程组     会话       认识会话       会话ID       创建会话 控制终端     作业控制       作业(job)和作业控制(Job Control)       作业号及作业过程…

QT5.14 QML串口助手

基于 QML的 串口调试助手 这个代码有缺失&#xff0c;补了部分代码 ASCII HEX 工程共享&#xff0c; Qt版本 5.14.1 COM_QML 通过百度网盘分享的文件&#xff1a;COM_QML.zip 链接&#xff1a;https://pan.baidu.com/s/1MH2d6gIPDSoaX-syVWZsww?pwd5tge 提取码&#xff1a;…

IOS ARKit进行图像识别

先讲一下基础控涧&#xff0c;资源的话可以留言&#xff0c;抽空我把它传到GitHub上&#xff0c;这里没写收积分&#xff0c;竟然充值才能下载&#xff0c;我下载也要充值&#xff0c;牛&#xff01; ARSCNView 可以理解画布或者场景 1 配置 ARWorldTrackingConfiguration AR追…

C语言第十五周课——课堂练习

目录 1.输出特定图形 2.求三个数的最小值 3.思考题 1.输出特定图形 要求&#xff1a;输出下面形状在控制台 * * * * * * * * * * * * * * * #include <stdio.h> int main() {int i, j;// 外层循环控制行数for (i 1; i < 5; i){// 内层循环控制每行的星号个数for (…

数据结构 (20)二叉树的遍历与线索化

一、二叉树的遍历 遍历是对树的一种最基本的运算&#xff0c;所谓遍历二叉树&#xff0c;就是按一定的规则和顺序走遍二叉树的所有节点&#xff0c;使每一个节点都被访问一次&#xff0c;而且只被访问一次。二叉树的遍历方式主要有四种&#xff1a;前序遍历、中序遍历、后序遍历…

sscanf与sprintf函数

本期介绍&#x1f356; 主要介绍&#xff1a;sscanf()、sprintf()这对输入/输出函数&#xff0c;并详细讲解了这两个函数的应用场景。 概述&#x1f356; 在C语言的输出和输入库中&#xff0c;有三对及其相似的库函数&#xff1a;printf()、scanf()、fprintf()、fscanf()、spri…

Linux条件变量线程池详解

一、条件变量 【互斥量】解决了线程间同步的问题&#xff0c;避免了多线程对同一块临界资源访问产生的冲突&#xff0c;但同一时刻对临界资源的访问&#xff0c;不论是生产者还是消费者&#xff0c;都需要竞争互斥锁&#xff0c;由此也带来了竞争的问题。即生产者和消费者、消费…

【错误记录】jupyter notebook打开后服务器错误Forbidden问题

如题&#xff0c;在Anaconda Prompt里输入jupyter notebook后可以打开浏览器&#xff0c;但打开具体项目后就会显示“服务器错误&#xff1a;Forbidden”&#xff0c;终端出现&#xff1a; tornado.web.HTTPError: HTTP 403: Forbidden 查看jupyter-server和jupyter notebook版…

shodan2-批量查找CVE-2019-0708漏洞

声明&#xff01; 学习视频来自B站up主 泷羽sec 有兴趣的师傅可以关注一下&#xff0c;如涉及侵权马上删除文章&#xff0c;笔记只是方便各位师傅的学习和探讨&#xff0c;文章所提到的网站以及内容&#xff0c;只做学习交流&#xff0c;其他均与本人以及泷羽sec团队无关&#…

PostgreSQL实现透视表查询

PostgreSQL 8.3版本发布时&#xff0c;引入了一个名为tablefunc的新扩展。这个扩展提供了一组非常有趣的函数。其中之一是交叉表函数&#xff0c;用于创建数据透视表。这就是我们将在本文中讨论的内容。 需求说明 解释此函数如何工作的最简单方法是使用带有数据透视表的示例…

使用Tauri创建桌面应用

当前是在 Windows 环境下 1.准备 系统依赖项 Microsoft C 构建工具WebView2 (Windows10 v1803 以上版本不用下载&#xff0c;已经默认安装了) 下载安装 Rust下载安装 Rust 需要重启终端或者系统 重新打开cmd&#xff0c;键入rustc --version&#xff0c;出现 rust 版本号&…

【掩体计划——DFS+缩点】

题目 代码 #include <bits/stdc.h> using namespace std; const int N 1e5 10; vector<vector<int>> g; bool st[N]; int ans 1e9; bool dfs(int f, int u, int dis) {bool is 1;for (auto j : g[u]){if (j f)continue;is & dfs(u, j, dis (g[u].…