java post请求发送文件流
时间: 2023-11-24 18:50:23 浏览: 47
以下是Java中使用HttpClient发送POST请求并上传文件流的示例代码:
```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.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
public class HttpUtil {
public static String postFile(String url, Map<String, String> params, Map<String, File> files) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 设置请求参数
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("text/plain", Charset.forName("UTF-8"))));
}
// 设置文件流
for (Map.Entry<String, File> entry : files.entrySet()) {
builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
EntityUtils.consume(responseEntity);
return result;
}
}
```
使用示例:
```java
Map<String, String> params = new HashMap<>();
params.put("param1", "张三");
Map<String, File> files = new HashMap<>();
files.put("file1", new File("path/to/file1"));
files.put("file2", new File("path/to/file2"));
String result = HttpUtil.postFile("http://example.com/upload", params, files);
System.out.println(result);
```