当前位置: 首页 > news >正文

HttpURLConnection发送各种内容格式

通过java.net.HttpURLConnection类实现http post发送Content-Type为multipart/form-data的请求。

json处理使用com.fasterxml.jackson

图片压缩使用net.coobird.thumbnailator

log使用org.slf4j

一些静态变量

private static final Charset charset = StandardCharsets.UTF_8;public enum Method {POST, GET}private static final Logger logger = LoggerFactory.getLogger(HttpHandler.class);

 自定义一些header

public static JsonNode getResponseWithHeaders(String urlString, Map<String, String> headerMap) throws HttpAccessException {try {
//            logger.debug("Requesting: {}", urlString);URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);
//            connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);connection.setRequestMethod("GET");if (headerMap != null) {headerMap.entrySet().forEach((header) -> {connection.setRequestProperty(header.getKey(), header.getValue());});}int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {return JsonUtil.getObjectMapper().readTree(new InputStreamReader(connection.getInputStream(), charset));} else {logger.error("Bad response code: {}", responseCode);throw new HttpAccessException("Bad response code: " + responseCode);}} catch (MalformedURLException e) {throw new HttpAccessException("Malformed url", e);} catch (JsonProcessingException parseException) {throw new HttpAccessException("Failed to parse response as JSON", parseException);} catch (IOException e) {throw new HttpAccessException("IOException", e);}}

get/post application/json 并接收application/json

public static JsonNode requestJsonResponse(String urlString, Method method, String body) throws HttpAccessException {try {
//            logger.debug("Requesting: {}", urlString);URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);connection.setRequestMethod(method == Method.POST ? "POST" : "GET");if (body != null) {OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset);logger.debug("Sending payload: {}", body);writer.write(body);writer.close();}int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {return JsonUtil.getObjectMapper().readTree(new InputStreamReader(connection.getInputStream(), charset));} else {logger.error("Bad response code: {}", responseCode);throw new HttpAccessException("Bad response code: " + responseCode);}} catch (MalformedURLException e) {throw new HttpAccessException("Malformed url", e);} catch (JsonProcessingException parseException) {throw new HttpAccessException("Failed to parse response as JSON", parseException);} catch (IOException e) {throw new HttpAccessException("IOException", e);}}public <T> T postReadClassResponse(String urlString, Object body, Class<T> responseClass) throws HttpAccessException {try {
//            logger.debug("Requesting: {}", urlString);URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON_VALUE);connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON_VALUE);connection.setRequestMethod("POST");objectMapper.writeValue(connection.getOutputStream(), body);int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {return objectMapper.readValue(connection.getInputStream(), responseClass);
//                return objectMapper.readTree(new InputStreamReader(connection.getInputStream(), charset));} else {
//                log.error("Bad response code: {}", responseCode);throw new HttpAccessException("Bad response code: " + responseCode);}} catch (MalformedURLException e) {throw new HttpAccessException("Malformed url", e);} catch (JsonProcessingException parseException) {throw new HttpAccessException("Failed to parse response as JSON", parseException);} catch (IOException e) {throw new HttpAccessException("IOException", e);}}

post application/x-www-form-urlencoded

public static String postApplicationFormUrlencoded(String urlString, Map<String, Object> body) throws HttpAccessException {StringBuilder sb = new StringBuilder();if (body != null && !body.isEmpty()) {body.entrySet().forEach(e -> {sb.append(e.getKey()).append('=');sb.append(e.getValue()).append('&');});sb.deleteCharAt(sb.length() - 1);}try {URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestProperty("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);connection.setRequestProperty("Accept", MediaType.WILDCARD);connection.setRequestMethod("POST");OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset);writer.write(sb.toString());writer.close();if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));StringBuilder buffer = new StringBuilder();String line;while ((line = reader.readLine()) != null) {buffer.append(line);}return buffer.toString();} else {int code = connection.getResponseCode();logger.error("Bad response code: {}", code);throw new HttpAccessException("Bad response code: " + code);}} catch (MalformedURLException e) {throw new HttpAccessException("Malformed url", e);} catch (IOException e) {throw new HttpAccessException("IOException", e);}}

加载图片并压缩

public static byte[] requestImg(String urlString, int width, int height) throws HttpAccessException {try {
//            logger.debug("Requesting: {}", urlString);URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestMethod("GET");if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {var inStream = connection.getInputStream();var outStream = new ByteArrayOutputStream();if (width > 0 & height > 0) {try {//压缩Thumbnailator.createThumbnail(inStream, outStream, width, height);inStream.close();return outStream.toByteArray();} catch (IOException ex) {logger.warn("Thumbnailator error, url:", urlString, ex);}}byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return outStream.toByteArray();} else {int code = connection.getResponseCode();logger.error("Bad response code: {}", code);throw new HttpAccessException("Bad response code: " + code);}} catch (MalformedURLException e) {throw new HttpAccessException("Malformed url", e);} catch (IOException e) {throw new HttpAccessException("IOException", e);}}

post application/json 并接收byte array

public static byte[] postTryReadImg(String urlString, JsonNode body) throws HttpAccessException {try {
//            logger.debug("Requesting: {}", urlString);URL url = new URL(urlString);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestMethod("POST");if (body != null) {OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset);logger.debug("Sending payload: {}", body);writer.write(body.toString());writer.close();}if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {var inStream = connection.getInputStream();var outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}inStream.close();return outStream.toByteArray();} else {int code = connection.getResponseCode();logger.error("Bad response code: {}", code);throw new HttpAccessException("Bad response code: " + code);}} catch (MalformedURLException e) {throw new HttpAccessException("Malformed url", e);} catch (IOException e) {throw new HttpAccessException("IOException", e);}}

post multipart/form-data 并接收json

public static HttpPostMultipart buildMultiPartRequest(String requestURL, Map<String, String> headers, String boundary) throws Exception {return new HttpPostMultipart(requestURL, headers, boundary);}public static class HttpPostMultipart {private final String boundary;private static final String LINE_FEED = "\r\n";private HttpURLConnection httpConn;//        private String charset;private OutputStream outputStream;private PrintWriter writer;/*** 构造初始化 http 请求,content type设置为multipart/form-data*/private HttpPostMultipart(String requestURL, Map<String, String> headers, String boundary) throws Exception {
//            this.charset = charset;if (StringUtil.isStringEmpty(boundary)) {boundary = UUID.randomUUID().toString();}this.boundary = boundary;URL url = new URL(requestURL);httpConn = (HttpURLConnection) url.openConnection();httpConn.setUseCaches(false);httpConn.setDoOutput(true);    // indicates POST methodhttpConn.setDoInput(true);httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);if (headers != null && headers.size() > 0) {Iterator<String> it = headers.keySet().iterator();while (it.hasNext()) {String key = it.next();String value = headers.get(key);httpConn.setRequestProperty(key, value);}}outputStream = httpConn.getOutputStream();
//            writer = new DataOutputStream(outputStream);writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);}/*** 添加form字段到请求*/public void addFormField(String name, String value) throws Exception {writer.append("--" + boundary).append(LINE_FEED);writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);writer.append(LINE_FEED);writer.append(value).append(LINE_FEED);
//            writer.write(sb.toString().getBytes());writer.flush();}/*** 添加文件*/public void addFilePart(String fieldName, String fileName, InputStream fileStream) throws Exception {writer.append("--").append(boundary).append(LINE_FEED);writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"").append(LINE_FEED);writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
//            sb.append("Content-Transfer-Encoding: binary").append(LINE_FEED);writer.append(LINE_FEED);
//            writer.write(sb.toString().getBytes());writer.flush();byte[] bufferOut = new byte[1024];if (fileStream != null) {int bytesRead = -1;while ((bytesRead = fileStream.read(bufferOut)) != -1) {outputStream.write(bufferOut, 0, bytesRead);}
//                while (fileStream.read(bufferOut) != -1) {
//                    writer.write(bufferOut);
//                }fileStream.close();}//            outputStream.flush();writer.append(LINE_FEED);writer.flush();}/*** Completes the request and receives response from the server.*/public JsonNode finish() throws Exception {writer.flush();writer.append("--").append(boundary).append("--").append(LINE_FEED);
//            writer.write(("--" + boundary + "--" + LINE_FEED).getBytes());writer.close();// checks server's status code firstint responseCode = httpConn.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {return JsonUtil.getObjectMapper().readTree(new InputStreamReader(httpConn.getInputStream()));} else {logger.error("Bad response code: {}", responseCode);throw new HttpAccessException("Bad response code: " + responseCode);}}}

相关文章:

HttpURLConnection发送各种内容格式

通过java.net.HttpURLConnection类实现http post发送Content-Type为multipart/form-data的请求。 json处理使用com.fasterxml.jackson 图片压缩使用net.coobird.thumbnailator log使用org.slf4j 一些静态变量 private static final Charset charset StandardCharsets.UTF_8;…...

摇杆控制人物移动

摇杆控制人物移动 一、UI搭建二、3d模型搭建三、脚本JoyStickBar.csPlayerController.cs 工程在我资源里名字叫Joystickbar.unitypackage [连接](https://download.csdn.net/download/qq_42194657/12043019?spm1001.2014.3001.5503) 一、UI搭建 JoyStickBar是图片背景 JoySt…...

Jenkins自动化部署之后端

准备工作参考本人另外几篇Jenkins相关的文章 新建任务 添加参数配置 字符串参数&#xff1a;分支名称 多选框&#xff1a;项目名称&#xff08;Extended Choice Parameter插件必备&#xff0c;插件安装参考我另外的文章&#xff09; 这个分割规则自定义。只要根据Jenkins…...

Could not resolve com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.28.

1、首先进入阿里云maven仓库&#xff0c;在搜索栏输入无法下载的依赖名称&#xff0c;查询现有版本号&#xff0c;可以看到这里有2.9.34。 2、在build.gradle(Project)的buildscript闭包下替换为阿里云maven仓库&#xff1a; maven { url https://www.jitpack.io } maven { u…...

RK3588平台开发系列讲解(AI 篇)RKNN rknn_query函数详细说明

文章目录 一、查询 SDK 版本二、查询输入输出 tensor 个数三、查询输入 tensor 属性(用于通用 API 接口)四、查询输出 tensor 属性(用于通用 API 接口)五、查询模型推理的逐层耗时六、查询模型推理的总耗时七、查询模型的内存占用情况八、查询模型里用户自定义字符串九、查询原…...

15个主流设计灵感网站,激发你的创作灵感!

即时设计 即时设计是一种强大的云设计工具&#xff0c;已成为许多设计师、产品经理和开发人员的首选工具之一。即时设计用户可以使用内置的工具和功能快速创建和编辑设计&#xff0c;或与其他用户共享和合作。此外&#xff0c;即时设计还有一个丰富的资源社区&#xff0c;为用…...

Matlab:解非线性方程组

1、基于问题求解非线性方程组 例&#xff1a; xoptimvar(x,2); %将x定义为一个二元素优化变量 eq1exp(-exp(-(x(1)x(2))))x(2)*(1x(1)^2); %创建第一个方程作为优化等式表达式 eq2x(1)*cos(x(2))x(2)*sin(x(1))1/2; %创建第二个方程作为优化等式表达式 probe…...

面向 AI,重塑云基础设施、存储、芯片、Serverless……2023亚马逊云科技re:Invent中国行

一年一度亚马逊云科技重要的技术盛会 re:Invent 刚落下帷幕&#xff0c;2023 亚马逊云科技 re:Invent 中国行就将其中重要的信息与内容带给了中国市场和用户。作为全球的云计算巨头&#xff0c;今年亚马逊云科技可以说全面加码 AI&#xff0c;例如发布完整的端到端生成式 AI 技…...

【JDK新特性】JDK和Springboot各版本新特性介绍

目录 参考资料 以下是一些较新版本的JDK的主要新特性介绍&#xff1a; JDK 8&#xff1a; Lambda 表达式&#xff1a;引入了函数式编程的概念&#xff0c;使得代码更简洁、可读性更强。Stream API&#xff1a;提供了一种高效处理集合数据的方式&#xff0c;支持并行处理。默认…...

tomcat剖析:开篇

一、简介 本专栏为解析tomcat的专栏&#xff0c;用于一步步的从构建到执行&#xff0c;再到剖析tomcat的内部构造&#xff0c;然后再加上自己的理解&#xff0c;从0到1去认识我们日常开发中不可或缺的web容器&#xff0c;希望对之后的软件设计能够有所启示。 二、步骤 2.1构…...

华为路由器:DHCP配置

在大型企业网络中&#xff0c;会有大量的主机获取IP地址等网络参数。如果采用手工配置&#xff0c;则工作量大不好管理&#xff0c;若用户擅自更改网络参数&#xff0c;则容易导致IP冲突。 因此使用动态主机配置协议&#xff08;DHCP&#xff09;可以减少管理员的工作量&#x…...

(企业 / 公司项目)微服务OpenFeign怎么实现服务间调用?(含面试题)

Feign: 远程调用组件使用步骤&#xff0c;理解上面的图  后台系统中, 微服务和微服务之间的调用可以通过Feign组件来完成.  Feign组件集成了Ribbon负载均衡策略(默认开启的, 使用轮询机制),Hystrix熔断器 (默认关闭的, 需要通过配置文件进行设置开启)  被调用的微服务…...

数据结构:图文详解 树与二叉树(树与二叉树的概念和性质,存储,遍历)

目录 一.树的概念 二.树中重要的概念 三.二叉树的概念 满二叉树 完全二叉树 四.二叉树的性质 五.二叉树的存储 六.二叉树的遍历 前序遍历 中序遍历 后序遍历 一.树的概念 树是一种非线性数据结构&#xff0c;它由节点和边组成。树的每个节点可以有零个或多个子节点…...

DM工作笔记-在windows下对DM7进行库还原恢复

提供了这些备份数据 在windows平台上&#xff0c;将这些备份数据还原到新库中。 首先实例得先停掉&#xff1a; 使用的软件console.exe&#xff1a; 重要步骤&#xff1a;①获取备份&#xff1b;②还原&#xff1b;③恢复 记住DMAP方式这个不要勾选&#xff0c;然后再获取备份…...

STM32软硬件CRC测速对比

硬件CRC配置 以及软硬件CRC速度对比 使用CUBEMX配置默认使用的是CRC32&#xff0c;从库中可以看出这一点 HAL库提供了以下两个计算函数 HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); 这个函数用于在已有的CRC校验结果的基础上累积…...

第九部分 图论

目录 例 相关概念 握手定理 例1 图的度数列 例 无向图的连通性 无向图的连通度 例2 例3 有向图D如图所示&#xff0c;求 A, A2, A3, A4&#xff0c;并回答诸问题&#xff1a; 中间有几章这里没有写&#xff0c;感兴趣可以自己去学&#xff0c;组合数学跟高中差不多&#xff0c…...

如何用java实现对java虚拟机的性能监控?

要使用Java实现对Java虚拟机&#xff08;JVM&#xff09;的性能监控&#xff0c;可以使用Java Management Extensions&#xff08;JMX&#xff09;来获取和监控JVM的各种指标。以下是一个简单的示例代码&#xff0c;演示如何使用JMX监控JVM的内存使用情况&#xff1a; import …...

电路设计(7)——窗口比较器的multism仿真

1.功能设计 构建一个窗口比较器的电路&#xff0c;在输入电压大于3.5v&#xff0c;小于0.8v时&#xff0c;蜂鸣器报警&#xff0c;输入电压在0.8v到3.5v之间时&#xff0c;不报警。 整体电路如下&#xff1a; 2.设计思路 在输入端&#xff0c;采取电阻分压的方式&#xff0c;输…...

前端已死?探讨人工智能与低代码对前端的影响

文章目录 每日一句正能量前言前端行业究竟是好是坏&#xff1f;数字化转型的当下前端工程师该何去何从&#xff1f; 想要入行前端先认清这三个事实 后记 每日一句正能量 人的结构就是相互支撑&#xff0c;众人的事业需要每个人的参与。 前言 随着人工智能和低代码的崛起&#…...

树莓派,opencv,Picamera2利用舵机云台追踪人脸(PID控制)

一、需要准备的硬件 Raspiberry Pi 4b两个SG90 180度舵机&#xff08;注意舵机的角度&#xff0c;最好是180度且带限位的&#xff0c;切勿选360度舵机&#xff09;二自由度舵机云台&#xff08;如下图&#xff09;Raspiberry CSI 摄像头 组装后的效果&#xff1a; 二、项目目…...

应用升级/灾备测试时使用guarantee 闪回点迅速回退

1.场景 应用要升级,当升级失败时,数据库回退到升级前. 要测试系统,测试完成后,数据库要回退到测试前。 相对于RMAN恢复需要很长时间&#xff0c; 数据库闪回只需要几分钟。 2.技术实现 数据库设置 2个db_recovery参数 创建guarantee闪回点&#xff0c;不需要开启数据库闪回。…...

RocketMQ延迟消息机制

两种延迟消息 RocketMQ中提供了两种延迟消息机制 指定固定的延迟级别 通过在Message中设定一个MessageDelayLevel参数&#xff0c;对应18个预设的延迟级别指定时间点的延迟级别 通过在Message中设定一个DeliverTimeMS指定一个Long类型表示的具体时间点。到了时间点后&#xf…...

进程地址空间(比特课总结)

一、进程地址空间 1. 环境变量 1 &#xff09;⽤户级环境变量与系统级环境变量 全局属性&#xff1a;环境变量具有全局属性&#xff0c;会被⼦进程继承。例如当bash启动⼦进程时&#xff0c;环 境变量会⾃动传递给⼦进程。 本地变量限制&#xff1a;本地变量只在当前进程(ba…...

Golang 面试经典题:map 的 key 可以是什么类型?哪些不可以?

Golang 面试经典题&#xff1a;map 的 key 可以是什么类型&#xff1f;哪些不可以&#xff1f; 在 Golang 的面试中&#xff0c;map 类型的使用是一个常见的考点&#xff0c;其中对 key 类型的合法性 是一道常被提及的基础却很容易被忽视的问题。本文将带你深入理解 Golang 中…...

工业安全零事故的智能守护者:一体化AI智能安防平台

前言&#xff1a; 通过AI视觉技术&#xff0c;为船厂提供全面的安全监控解决方案&#xff0c;涵盖交通违规检测、起重机轨道安全、非法入侵检测、盗窃防范、安全规范执行监控等多个方面&#xff0c;能够实现对应负责人反馈机制&#xff0c;并最终实现数据的统计报表。提升船厂…...

MongoDB学习和应用(高效的非关系型数据库)

一丶 MongoDB简介 对于社交类软件的功能&#xff0c;我们需要对它的功能特点进行分析&#xff1a; 数据量会随着用户数增大而增大读多写少价值较低非好友看不到其动态信息地理位置的查询… 针对以上特点进行分析各大存储工具&#xff1a; mysql&#xff1a;关系型数据库&am…...

2021-03-15 iview一些问题

1.iview 在使用tree组件时&#xff0c;发现没有set类的方法&#xff0c;只有get&#xff0c;那么要改变tree值&#xff0c;只能遍历treeData&#xff0c;递归修改treeData的checked&#xff0c;发现无法更改&#xff0c;原因在于check模式下&#xff0c;子元素的勾选状态跟父节…...

【C++从零实现Json-Rpc框架】第六弹 —— 服务端模块划分

一、项目背景回顾 前五弹完成了Json-Rpc协议解析、请求处理、客户端调用等基础模块搭建。 本弹重点聚焦于服务端的模块划分与架构设计&#xff0c;提升代码结构的可维护性与扩展性。 二、服务端模块设计目标 高内聚低耦合&#xff1a;各模块职责清晰&#xff0c;便于独立开发…...

tree 树组件大数据卡顿问题优化

问题背景 项目中有用到树组件用来做文件目录&#xff0c;但是由于这个树组件的节点越来越多&#xff0c;导致页面在滚动这个树组件的时候浏览器就很容易卡死。这种问题基本上都是因为dom节点太多&#xff0c;导致的浏览器卡顿&#xff0c;这里很明显就需要用到虚拟列表的技术&…...

CMake控制VS2022项目文件分组

我们可以通过 CMake 控制源文件的组织结构,使它们在 VS 解决方案资源管理器中以“组”(Filter)的形式进行分类展示。 🎯 目标 通过 CMake 脚本将 .cpp、.h 等源文件分组显示在 Visual Studio 2022 的解决方案资源管理器中。 ✅ 支持的方法汇总(共4种) 方法描述是否推荐…...