当前位置: 首页 > 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; 二、项目目…...

多云管理“拦路虎”:深入解析网络互联、身份同步与成本可视化的技术复杂度​

一、引言&#xff1a;多云环境的技术复杂性本质​​ 企业采用多云策略已从技术选型升维至生存刚需。当业务系统分散部署在多个云平台时&#xff0c;​​基础设施的技术债呈现指数级积累​​。网络连接、身份认证、成本管理这三大核心挑战相互嵌套&#xff1a;跨云网络构建数据…...

MPNet:旋转机械轻量化故障诊断模型详解python代码复现

目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...

Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误

HTTP 状态码 406 (Not Acceptable) 和 500 (Internal Server Error) 是两类完全不同的错误&#xff0c;它们的含义、原因和解决方法都有显著区别。以下是详细对比&#xff1a; 1. HTTP 406 (Not Acceptable) 含义&#xff1a; 客户端请求的内容类型与服务器支持的内容类型不匹…...

练习(含atoi的模拟实现,自定义类型等练习)

一、结构体大小的计算及位段 &#xff08;结构体大小计算及位段 详解请看&#xff1a;自定义类型&#xff1a;结构体进阶-CSDN博客&#xff09; 1.在32位系统环境&#xff0c;编译选项为4字节对齐&#xff0c;那么sizeof(A)和sizeof(B)是多少&#xff1f; #pragma pack(4)st…...

土地利用/土地覆盖遥感解译与基于CLUE模型未来变化情景预测;从基础到高级,涵盖ArcGIS数据处理、ENVI遥感解译与CLUE模型情景模拟等

&#x1f50d; 土地利用/土地覆盖数据是生态、环境和气象等诸多领域模型的关键输入参数。通过遥感影像解译技术&#xff0c;可以精准获取历史或当前任何一个区域的土地利用/土地覆盖情况。这些数据不仅能够用于评估区域生态环境的变化趋势&#xff0c;还能有效评价重大生态工程…...

python执行测试用例,allure报乱码且未成功生成报告

allure执行测试用例时显示乱码&#xff1a;‘allure’ &#xfffd;&#xfffd;&#xfffd;&#xfffd;&#xfffd;ڲ&#xfffd;&#xfffd;&#xfffd;&#xfffd;ⲿ&#xfffd;&#xfffd;&#xfffd;Ҳ&#xfffd;&#xfffd;&#xfffd;ǿ&#xfffd;&am…...

【生成模型】视频生成论文调研

工作清单 上游应用方向&#xff1a;控制、速度、时长、高动态、多主体驱动 类型工作基础模型WAN / WAN-VACE / HunyuanVideo控制条件轨迹控制ATI~镜头控制ReCamMaster~多主体驱动Phantom~音频驱动Let Them Talk: Audio-Driven Multi-Person Conversational Video Generation速…...

push [特殊字符] present

push &#x1f19a; present 前言present和dismiss特点代码演示 push和pop特点代码演示 前言 在 iOS 开发中&#xff0c;push 和 present 是两种不同的视图控制器切换方式&#xff0c;它们有着显著的区别。 present和dismiss 特点 在当前控制器上方新建视图层级需要手动调用…...

RSS 2025|从说明书学习复杂机器人操作任务:NUS邵林团队提出全新机器人装配技能学习框架Manual2Skill

视觉语言模型&#xff08;Vision-Language Models, VLMs&#xff09;&#xff0c;为真实环境中的机器人操作任务提供了极具潜力的解决方案。 尽管 VLMs 取得了显著进展&#xff0c;机器人仍难以胜任复杂的长时程任务&#xff08;如家具装配&#xff09;&#xff0c;主要受限于人…...

MySQL:分区的基本使用

目录 一、什么是分区二、有什么作用三、分类四、创建分区五、删除分区 一、什么是分区 MySQL 分区&#xff08;Partitioning&#xff09;是一种将单张表的数据逻辑上拆分成多个物理部分的技术。这些物理部分&#xff08;分区&#xff09;可以独立存储、管理和优化&#xff0c;…...