记录 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");
}
}