java HttpClient 发送MultipartFile
时间: 2023-12-12 21:34:41 浏览: 134
以下是Java使用HttpClient发送MultipartFile的示例代码:
```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 org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
public class HttpClientUtil {
public static String sendMultipartFile(String url, MultipartFile file, String paramStr) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
// 构建请求参数
FileBody fileBody = new FileBody(convert(file));
StringBody stringBody = new StringBody(paramStr, ContentType.create("text/plain", Charset.forName("UTF-8")));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("file", fileBody)
.addPart("paramStr", stringBody)
.build();
httpPost.setEntity(reqEntity);
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
String result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
return result;
}
private static File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
file.transferTo(convFile);
return convFile;
}
}
```
其中,`sendMultipartFile`方法接收三个参数:请求URL、MultipartFile文件和请求参数。该方法使用HttpClient发送POST请求,将文件和参数一起发送到指定的URL,并返回响应结果。
阅读全文