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



相关推荐
Hilaku2 分钟前
用好了 defineProps 才叫会用 Vue3,90% 的写法都错了
前端·javascript·vue.js
英宋4 分钟前
ckeditor5的研究 (2):对 CKEditor5 进行设计,并封装成一个可用的 vue 组件
前端·javascript
古夕5 分钟前
搞定滚动穿透
前端·javascript
魔镜魔镜_谁是世界上最漂亮的小仙女5 分钟前
java-集合
java·后端·程序员
英宋5 分钟前
ckeditor5的研究 (3):初步使用 CKEditor5 的 事件系统 和 API
前端·javascript
真实的菜6 分钟前
消息队列高级特性与原理:解锁分布式系统的底层逻辑
java
若水不如远方8 分钟前
java范型
java
Danta10 分钟前
从 0 开始学习 Three.js(2)😁
前端·javascript·three.js
凌辰揽月10 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
就是我14 分钟前
开发“业务组件库”,该从哪里入手?
前端·javascript·面试