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

HttpURLConnection构造请求体传文件

HttpURLConnection构造请求体传文件

在Java中,使用HttpURLConnection构造请求体传输文件,你需要做以下几步:
1、创建URL对象指向你想要请求的资源。
2、通过URL打开连接,转换为HttpURLConnection实例。
3、设置请求方法为POST。
4、设置请求头,包括Content-Type(通常为multipart/form-data)和边界值。
5、创建DataOutputStream来写入请求体。
6、构造每个表单项的数据,包括文件内容和文本字段。
7、读取服务器响应。
8、关闭连接。

以下是一个简化的示例代码:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;public class HttpUploadFileExample {public static void main(String[] args) throws IOException {String boundary = "*****";String endBoundary = "--" + boundary + "--";URL url = new URL("http://example.com");HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setRequestMethod("POST");connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);try (OutputStream output = connection.getOutputStream();PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);) {// 添加文件File file = new File("/path/to/file");writer.append("--" + boundary).append(CRLF);writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(CRLF);writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(CRLF);writer.append(CRLF).flush();Files.copy(file.toPath(), output);output.flush(); // 确保文件内容被发送writer.append(CRLF).flush(); // 写入换行,表示文件结束// 添加表单字段writer.append("--" + boundary).append(CRLF);writer.append("Content-Disposition: form-data; name=\"fieldName\"").append(CRLF);writer.append(CRLF).append("value").append(CRLF).flush();// 结束边界writer.append(endBoundary).append(CRLF).flush();}int responseCode = connection.getResponseCode();System.out.println("Response Code: " + responseCode);// 处理服务器响应...connection.disconnect();}
}

CRLF是Carriage-Return Line-Feed的缩写,意思是回车换行,就是回车。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

http://www.lryc.cn/news/464432.html

相关文章:

  • STM32传感器模块编程实践(九) VL53L0X激光红外测距传感器简介及驱动源码
  • fastjson注解说明,fastjson注解有那些?fastjson是java的json序列化和反序列化工具包
  • VIT:论文关键点解读与常见疑问
  • ArcGIS无插件加载(无偏移)在线天地图高清影像与街道地图指南
  • 工业相机选型(自用笔记)
  • 【网安笔记】4种拒绝服务攻击
  • WPF 的组件数据绑定详解
  • 房子,它或许是沃土
  • 【Golang】Go语言http编程底层逻辑实现原理与实战
  • SOLIDWORKS参数化软件
  • 上位机开发常用技术 C# Task 线程 开始,暂停,继续,停止
  • MySQL 密码忘记了怎么办?
  • Java中常见的自带数据结构类
  • 数据结构——链表,哈希表
  • 如何使用Python对Excel、CSV文件完成数据清洗与预处理?
  • 第8篇:网络安全基础
  • Flutter 中的 PopScope 小部件:全面指南
  • 视频剪辑的未来
  • 通过PHP与API的结合,开启电商数据集成的新篇章
  • 使用 CDN 后 Apache 的日志记录客户真实 IP
  • ORACLE 19C安装 RAC报错
  • 省心英语 3.9.9| 资源最全面的英语学习App
  • ruoyi框架动态切换数据库
  • iba Data Export 导出面板选项
  • 过滤器Filter的介绍和使用
  • JMeter之mqtt-jmeter 插件介绍
  • Nacos2.3.2在ubuntu中的部署
  • Xilinx远程固件升级(一)——QuickBoot方案
  • O(1)调度算法与CFS
  • SpringBoot——静态资源访问的四种方式