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

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.kler.cn/news/357349.html

相关文章:

  • 第T5周:Tensorflow实现运动鞋品牌识别
  • bat脚本banenr
  • 【C++】STL--list
  • [实时计算flink]数据库实时入仓快速入门
  • N1安装grafana
  • Elasticsearch Ingest Pipelines
  • (数据结构)单链表——C语言
  • 吴恩达深度学习笔记:卷积神经网络(Foundations of Convolutional Neural Networks)3.5-3.6
  • 十五、行为型(迭代器模式)
  • 探索GenAI/大模型评估与对比:AutoArena开源框架及产品介绍
  • Azure OpenAI 服务上线具有音频和语音功能的 GPT-4o-Realtime-Preview,免费申请试用
  • 文本生成视频技术:艺术与科学的交汇点
  • Perl打印9x9乘法口诀
  • 【练习题】设计循环队列
  • OJ-两个字符串间的最短路径问题
  • 在数据库中,`SELECT`, `FROM`, `JOIN`, `ON`, 和 `WHERE`各自的作用
  • csp普及组算法集训--Dfs
  • 一级注册消防工程师《消防安全技术实务》模拟试题及详解
  • 详解mac系统通过brew安装mongodb与使用
  • SpringCloud学习:Spring Cloud Alibaba Nacos(服务注册中心、配置管理中心)