java 发送form-data请求上传文件代码
时间: 2023-06-01 07:06:34 浏览: 110
我可以为您提供如下 Java 代码示例,用于发送 form-data 请求上传文件:
```
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FormDataUploader {
public static void main(String[] args) {
String url = "http://example.com/upload";
String fileName = "test.png";
File file = new File(fileName);
String boundary = Long.toHexString(System.currentTimeMillis());
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n");
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append("\r\n");
writer.append("\r\n");
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.flush();
inputStream.close();
writer.append("\r\n");
writer.append("--" + boundary + "--").append("\r\n");
writer.flush();
writer.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,上传的文件名和请求URL需要根据实际情况进行修改。
阅读全文