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的缩写,意思是回车换行,就是回车。



相关推荐
wuminyu5 分钟前
OpenJDK学习笔记:Native线程如何回调Java
java·linux·c语言·jvm·c++
骑着蜗牛撵大象32714 分钟前
AgentScope 搭大脑、Spring AI 当手脚:企业智能体推理与执行分层落地
java·人工智能·spring·智能体·工具调用·agentscope·模型编排
程序员小杰@33 分钟前
SpringBoot + SpringCloudAlibaba 日志 & 链路追踪 完整总结
java·spring boot·后端
EatFan1 小时前
2026 后端 AI 集成选型拆解:Spring AI 2.0、MCP 协议与 Agent 内嵌三条路径的决策要点
java·人工智能·spring
天远API2 小时前
零信任架构实战:基于天远运营商近3个月欠费次数构建自动化授信调额合规网关
java·人工智能·架构·自动化
SummerJokes2 小时前
Java 集合 List 全套实验|从基础增删改查到实体类存储
java·python·list
总要学点什么2 小时前
第128篇:镜头光晕与高光——把逆光太阳晕成会躲山的光斑
开发语言·javascript·数码相机·microsoft·材质·cesium
都在酒里3 小时前
STM32 Bootloader 实战:RS-485 固件升级与断电恢复
javascript·stm32·嵌入式硬件
长不大的杨瑞杰3 小时前
Spring AI 企业级 RAG 实战:检索、重排、结构化输出与提示注入防护
java·人工智能·spring·llm·rag·springai
阿凤213 小时前
学习java---流程控制篇
java·开发语言·学习