java multipart/form-data请求 上传下载
时间: 2023-09-12 22:11:30 浏览: 158
对于Java中的multipart/form-data请求,用于上传和下载文件,你可以使用Java的HttpURLConnection或Apache HttpClient库来完成。
首先,我们来看一下如何使用HttpURLConnection来发送multipart/form-data请求进行文件上传:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class MultipartUploader {
public static void main(String[] args) throws IOException {
// 请求URL
URL url = new URL("http://example.com/upload");
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// 设置请求头
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
// 构建请求体
try (OutputStream outputStream = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true)) {
// 添加文件参数
File file = new File("/path/to/file.txt");
writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n")
.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n")
.append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + "\r\n\r\n")
.flush();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
fileInputStream.close();
// 添加其他参数
writer.append("\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n")
.append("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
.append("John Doe\r\n")
.flush();
// 请求结束标志
writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--").flush();
}
// 获取响应
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 响应处理
} else {
// 错误处理
}
conn.disconnect();
}
}
```
上述代码中,我们使用`HttpURLConnection`创建了一个POST请求,并设置了请求头的`Content-Type`为`multipart/form-data`,同时构建了请求体包含文件和其他参数。发送请求后,可以通过`conn.getResponseCode()`获取响应码,进而对响应进行处理。
接下来,我将展示如何使用Apache HttpClient来发送multipart/form-data请求进行文件上传和下载:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.File;
import java.io.IOException;
public class MultipartUploader {
public static void main(String[] args) throws IOException {
// 创建HttpClient
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
// 创建HttpPost请求
HttpPost httpPost = new HttpPost("http://example.com/upload");
// 构建请求体
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 添加文件参数
File file = new File("/path/to/file.txt");
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
builder.addPart("file", fileBody);
// 添加其他参数
builder.addTextBody("name", "John Doe");
// 设置请求体
HttpEntity multipartEntity = builder.build();
httpPost.setEntity(multipartEntity);
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
// 处理响应
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// 响应处理
} else {
// 错误处理
}
}
}
}
```
上述代码中,我们使用了Apache HttpClient库来创建了一个HttpPost请求,然后通过`MultipartEntityBuilder`构建了请求体,添加了文件和其他参数。发送请求后,可以通过`response.getStatusLine().getStatusCode()`获取响应码,进而对响应进行处理。
至于文件下载的请求,你可以使用`HttpGet`请求来实现。具体代码类似于上述的文件上传示例,只需要将HttpPost替换为HttpGet,并设置请求URL即可。
希望这些示例代码能帮助到你进行multipart/form-data请求的文件上传和下载。
阅读全文