依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>
我这里是获取第三方接口的token,上传文件类型参数
public static String getToken(){
logger.info("token请求时间:" + DateUtil.formatDate(new Date(), DateUtil.PATTERN_YYYY_MM_DD_HH_MM_SS));
InputStream in = null;
String result = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost postTool = new HttpPost(GZ_BASE_URL);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//文件名
String fileName = platform+"_"+"TOKEN"+"_"+"ACCESS"+"_"+"REQ"+"_"+JwPushUtil.dateToLongyyyyMMddHHmmssSSS(new Date())+".json";
builder.addTextBody("filename", fileName, ContentType.TEXT_PLAIN);
JSONObject jsonObject = new JSONObject();
//参数添加到集合
jsonObject.put("platform",platform);
jsonObject.put("key",GZCompanyId);
//我这里是直接将json数据转成流,如果需要从本地读取数据的话可以先将文件读到文件流中
//String sTestsetFile="d://DDWLJH6D_TOKEN_ACCESS_REQ_20211202161720637.json";
//InputStream inputStream = new FileInputStream(sTestsetFile);
in = new ByteArrayInputStream(jsonObject.toString().getBytes());
builder.addBinaryBody(
"binFile",
in,
ContentType.APPLICATION_OCTET_STREAM,
fileName
);
//参数集合
postTool.addHeader("binfile-auth","DDWLJH6D");
HttpEntity multipart = builder.build();
postTool.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(postTool);
HttpEntity responseEntity = response.getEntity();
String sResponse= EntityUtils.toString(responseEntity, "UTF-8");
//打印请求返回的结果
System.out.println("Post 返回结果"+sResponse);
JSONObject json = JSONObject.parseObject(sResponse);
result = (String) json.get("token");
// 把文件加到HTTP的post请求中
//File f = new File(sTestsetFile);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("返回数据->"+result);
return result;
}