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

Vim 调用外部命令学习笔记

Vim 外部命令集成完全指南 文章目录 Vim 外部命令集成完全指南核心概念理解命令语法解析语法对比 常用外部命令详解文本排序与去重文本筛选与搜索高级 grep 搜索技巧文本替换与编辑字符处理高级文本处理编程语言处理其他实用命令 范围操作示例指定行范围处理复合命令示例 实用技…...

变量 varablie 声明- Rust 变量 let mut 声明与 C/C++ 变量声明对比分析

一、变量声明设计&#xff1a;let 与 mut 的哲学解析 Rust 采用 let 声明变量并通过 mut 显式标记可变性&#xff0c;这种设计体现了语言的核心哲学。以下是深度解析&#xff1a; 1.1 设计理念剖析 安全优先原则&#xff1a;默认不可变强制开发者明确声明意图 let x 5; …...

8k长序列建模,蛋白质语言模型Prot42仅利用目标蛋白序列即可生成高亲和力结合剂

蛋白质结合剂&#xff08;如抗体、抑制肽&#xff09;在疾病诊断、成像分析及靶向药物递送等关键场景中发挥着不可替代的作用。传统上&#xff0c;高特异性蛋白质结合剂的开发高度依赖噬菌体展示、定向进化等实验技术&#xff0c;但这类方法普遍面临资源消耗巨大、研发周期冗长…...

无法与IP建立连接,未能下载VSCode服务器

如题&#xff0c;在远程连接服务器的时候突然遇到了这个提示。 查阅了一圈&#xff0c;发现是VSCode版本自动更新惹的祸&#xff01;&#xff01;&#xff01; 在VSCode的帮助->关于这里发现前几天VSCode自动更新了&#xff0c;我的版本号变成了1.100.3 才导致了远程连接出…...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

《用户共鸣指数(E)驱动品牌大模型种草:如何抢占大模型搜索结果情感高地》

在注意力分散、内容高度同质化的时代&#xff0c;情感连接已成为品牌破圈的关键通道。我们在服务大量品牌客户的过程中发现&#xff0c;消费者对内容的“有感”程度&#xff0c;正日益成为影响品牌传播效率与转化率的核心变量。在生成式AI驱动的内容生成与推荐环境中&#xff0…...

【单片机期末】单片机系统设计

主要内容&#xff1a;系统状态机&#xff0c;系统时基&#xff0c;系统需求分析&#xff0c;系统构建&#xff0c;系统状态流图 一、题目要求 二、绘制系统状态流图 题目&#xff1a;根据上述描述绘制系统状态流图&#xff0c;注明状态转移条件及方向。 三、利用定时器产生时…...

涂鸦T5AI手搓语音、emoji、otto机器人从入门到实战

“&#x1f916;手搓TuyaAI语音指令 &#x1f60d;秒变表情包大师&#xff0c;让萌系Otto机器人&#x1f525;玩出智能新花样&#xff01;开整&#xff01;” &#x1f916; Otto机器人 → 直接点明主体 手搓TuyaAI语音 → 强调 自主编程/自定义 语音控制&#xff08;TuyaAI…...

【JavaSE】绘图与事件入门学习笔记

-Java绘图坐标体系 坐标体系-介绍 坐标原点位于左上角&#xff0c;以像素为单位。 在Java坐标系中,第一个是x坐标,表示当前位置为水平方向&#xff0c;距离坐标原点x个像素;第二个是y坐标&#xff0c;表示当前位置为垂直方向&#xff0c;距离坐标原点y个像素。 坐标体系-像素 …...

爬虫基础学习day2

# 爬虫设计领域 工商&#xff1a;企查查、天眼查短视频&#xff1a;抖音、快手、西瓜 ---> 飞瓜电商&#xff1a;京东、淘宝、聚美优品、亚马逊 ---> 分析店铺经营决策标题、排名航空&#xff1a;抓取所有航空公司价格 ---> 去哪儿自媒体&#xff1a;采集自媒体数据进…...