java发送http请求上传大文件
时间: 2023-08-07 22:08:30 浏览: 273
Java发送HTTP请求上传大文件可以使用Java自带的HTTP库(HttpURLConnection)或者第三方HTTP请求库(如Apache HttpClient、OkHttp)实现。以下是使用Java自带的HTTP库(HttpURLConnection)上传大文件的示例代码:
```java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUploadDemo {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api/upload");
// 创建HTTP连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头参数
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
// 设置是否向HttpURLConnection输出,默认false
connection.setDoOutput(true);
// 获取文件对象
File file = new File("path/to/your/file");
// 设置请求体参数
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
outputStream.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
// 读取文件内容并写入请求体
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
// 添加请求体结束标记
outputStream.writeBytes("\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n");
// 发送请求
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应内容
System.out.println(responseCode);
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请将URL和请求头参数替换为您要访问的API的实际值。其中,使用了DataOutputStream将文件内容写入请求体,以避免在内存中存储整个文件内容导致内存溢出。
阅读全文