以往的印象里面,实现附件上传需要有附件在磁盘里面存在(可能是见识浅薄),想着怎么去优化一下,避免落盘,就引入了这种方式,实现很容易,只是没有实践过,实践导致认知限制
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5</version>
</dependency>
public static void main(String[] args) {
String url = "http://IP:port/api/wechat/email";
Map<String, String> map = new HashMap<>();
map.put("mail", "[email protected]");
map.put("content", "请关注附件内容");
map.put("isHtml", "true");
map.put("title", "bian.yanmingtest");
uploadFileExcel(url, map);
}
public static String uploadFileExcel(String url, Map<String, String> params) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String resultString = "";
CloseableHttpResponse response = null;
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
for (String key : params.keySet()) {
builder.addPart(key,
new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
}
String fileStr = "姓名,性别 \nbym,0\n test,1";
byte[] fileBytes = fileStr.getBytes();
// ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);
builder.addPart("mfile",new ByteArrayBody(fileBytes,"test.csv"));
// builder.addPart("mfile", new InputStreamBody(byteArrayInputStream, "test.csv"));
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
response = client.execute(httpPost, HttpClientContext.create());
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println(resultString);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
http这块的经验总结
https://www.cnblogs.com/bingyimeiling/p/11820583.html