Java HttpURLConnection上传文件

记录 HttpURLConnection 上传文件

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 上传文件
 * @Author: zhuyu
 * @Date: 2024/3/2 12:27
 */
public class FileUploader {


    public static void main(String[] args) throws IOException {
        File fileToUpload = new File("path_to_your_file");
        String serverUrl = "http://yourserver/upload_endpoint";
        String fileParamName = "file"; // 文件对应的表单参数名
        Map<String, String> formParams = new HashMap<>();
        formParams.put("age", "20");
        formParams.put("name", "zhangsan");
        formParams.put("address", "beijing");

        uploadFile(serverUrl, fileToUpload, fileParamName, formParams);
    }

    /**
     * 上传文件(HttpURLConnection)
     * @param targetUrl
     * @param file
     * @param fileParamName
     * @param formParams
     * @return
     * @throws IOException
     */
    public static String uploadFile(String targetUrl, File file, String fileParamName, Map<String, String> formParams) throws IOException {
        String result = "";
        URL url = new URL(targetUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        try {
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 允许输出
            connection.setDoInput(true);  // 允许输入

            // 设置多部分表单数据的边界
            String boundary = "---------------------------" + System.currentTimeMillis();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            try (DataOutputStream dos = new DataOutputStream(connection.getOutputStream())) {
                // 写入每个表单参数
                for (Map.Entry<String, String> entry : formParams.entrySet()) {
                    writeBoundary(dos, boundary);
                    dos.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                    dos.writeBytes(entry.getValue() + "\r\n");
                }

                // 写入文件参数
                writeBoundary(dos, boundary);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + file.getName() + "\"\r\n");
                dos.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
                try (FileInputStream fis = new FileInputStream(file)) {
                    byte[] buffer = new byte[4096];
                    int length;
                    while ((length = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, length);
                    }
                }

                // 写入结束边界
                writeBoundary(dos, boundary, true);
            }

            // 获取服务器响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 处理服务器响应...
                result = connection.getResponseMessage();
            }else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
                System.out.println("File uploaded successfully.");
            }else {
                System.out.println("Failed to upload. Server returned HTTP response code: " + responseCode);
            }
        } finally {
            connection.disconnect();
        }
        return result;
    }

    private static void writeBoundary(DataOutputStream dos, String boundary) throws IOException {
        dos.writeBytes("--" + boundary + (false ? "--" : "") + "\r\n");
    }

    private static void writeBoundary(DataOutputStream dos, String boundary, boolean isLastPart) throws IOException {
        dos.writeBytes("--" + boundary + (isLastPart ? "--" : "") + "\r\n");
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值