HttpClientForm
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
/**
* @Author 楚璃轩
* @Date 2022/1/3 10:27
* @Description 以表单的形式提交
*/
public class HttpClientForm {
private static Logger logger = LoggerFactory.getLogger(HttpClientForm.class);
public static String accessHttpPost(String url, Map<String, JSONObject> map, File file) {
String requestJson = "";
//传入参数可以为file或者filePath,在此处做转换
//File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
try {
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//设置浏览器兼容模式
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//设置请求的编码格式
builder.setCharset(Consts.UTF_8);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
//添加文件
//builder.addBinaryBody("cover", cover);
if (file != null) {
InputStream fileInputStream = new FileInputStream(file);
builder.addBinaryBody("filename",fileInputStream, ContentType.MULTIPART_FORM_DATA, file.getName());
}
//json
if (map != null) {
ContentType strContent = ContentType.create("application/json", Charset.forName("UTF-8"));
for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
builder.addTextBody(entry.getKey(), JSONObject.toJSONString(entry.getValue()), strContent);
}
}
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
httpResponse = httpClient.execute(httppost);
requestJson = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源
try {
if (httpClient != null) {
httpClient.close();
}
if (httpResponse != null) {
httpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return requestJson;
}
}
Impl层
//某个字段内容生成附件->模拟表单以文件流形式传递
ResourceLoader resourceLoader = new DefaultResourceLoader();
//需要在【resources】目录下创建【template】目录和【fileContent.txt】文件
InputStream inputStream = resourceLoader.getResource("template/fileContent.txt").getInputStream();
//将文件转换为临时文件进行操作
File file = File.createTempFile("fileContent", ".txt");
try {
FileUtils.copyInputStreamToFile(inputStream, file);
} finally {
//关闭IO
IOUtils.closeQuietly(inputStream);
}
//将某个字段内容写入临时文件中
FileWriter writer;
try {
writer = new FileWriter(file);
writer.write("");//清空原文件内容
writer.write(某个字段);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
//存放接口响应结果
String response = "";
JSONObject jsonObject = new JSONObject();
jsonObject.put("字段",字段值);
jsonObject.put("字段",字段值);
//数据以map形式保存
Map<String, JSONObject> map = new HashMap<>();
map.put("字段", jsonObject);
try {
response = HttpClientForm.accessHttpPost(url,map,file);
} catch (Exception e) {
logger.error("请求接口失败", e);
}finally {
//删除临时文件
boolean result = file.delete();
if (result) {
logger.info("File is success delete.");
} else {
logger.info("File doesn't exist.");
}
}
pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>