Java HttpPost 数据流方式上传图片
时间: 2023-06-26 18:09:03 浏览: 171
Java中使用HttpPost实现数据流方式上传图片的步骤如下:
1. 创建HttpClient对象
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
```
2. 创建HttpPost对象,并设置请求URL
```java
HttpPost httpPost = new HttpPost("http://example.com/upload");
```
3. 创建HttpEntity对象,并设置上传的文件和参数
```java
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置文件参数
File file = new File("image.jpg");
entityBuilder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
// 设置其他参数
entityBuilder.addTextBody("name", "example");
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);
```
4. 执行HttpPost请求,并获取响应结果
```java
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
String response = EntityUtils.toString(responseEntity);
```
完整的代码示例:
```java
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ImageUploader {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/upload");
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// 设置文件参数
File file = new File("image.jpg");
entityBuilder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());
// 设置其他参数
entityBuilder.addTextBody("name", "example");
HttpEntity httpEntity = entityBuilder.build();
httpPost.setEntity(httpEntity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
String response = EntityUtils.toString(responseEntity);
System.out.println(response);
}
}
```
阅读全文