如何通过java代码发送文件表单http请求
1、引入包
<!-- http请求 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpcomponents.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpcomponents.version}</version>
</dependency>
2、文件表单请求
//单元测试
@Test
public void testUploadFile(){
String url="https://xx.xxx.com/api/openapi/select";
uploadFile(url,"C:\\Users\\xxxx\\Desktop\\test.txt","test文件.txt",null);
}
//文件表单上传
public String uploadFile(String url, String fileUrl, String fileParamName, Map<String, String> params) {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
.setConnectTimeout(timeout).setSocketTimeout(timeout).build();
httpPost.setConfig(requestConfig);
String resultString = "";
CloseableHttpResponse response = null;
try {
// 把文件转换成流对象 我这里用的是文件地址,所有用ByteArrayBody,可根据实际需要使用org.apache.http.entity.mime.content包下的类型
ByteArrayBody byteArrayBody = new ByteArrayBody(UrlUtil.bytes(fileUrl),fileParamName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 相当于<input type="file" name="file"/>
builder.addPart("file", byteArrayBody);
// 相当于<input type="text" name="userName" value=userName>
builder.addPart("name",
new StringBody(fileParamName, ContentType.create("text/plain", Consts.UTF_8)));
if (params != null) {
for (String key : params.keySet()) {
builder.addPart(key,
new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
}
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
response = client.execute(httpPost);
// 发起请求 并返回请求的响应
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
IoUtil.close(client);
IoUtil.close(response);
}
return resultString;
}
附org.apache.http.entity.mime.content: