httpclient 上传文件
时间: 2023-09-03 22:11:35 浏览: 147
你可以使用 HttpClient 来上传文件。下面是一个使用 HttpClient 上传文件的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.File;
import java.io.IOException;
public class FileUploader {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 添加文件参数
File file = new File("path/to/file.txt");
builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
try {
HttpResponse response = httpClient.execute(httpPost);
// 处理上传结果
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你需要将 `http://example.com/upload` 替换为你要上传文件的目标 URL,将 `"path/to/file.txt"` 替换为你要上传的文件路径。在这个示例中,我们使用了 HttpClient 4.x 版本的库进行文件上传。
阅读全文