上一篇文章“SpringBoot中接收form-data请求参数处理后请求外部接口”的有个会在本地创建文件夹的缺点,在本文中会得到解决。
本文背景是通过一个链接请求得到一份文件,再将文件转给外部的一个接口,请求的参数就是得到文件的请求地址。 重点在得到文件后的操作。
@Autowired
private GatewayParams gatewayParams;
private static final String QTKEN = "x-qys-accesstoken";
private static final String QTIME = "x-qys-timestamp";
private static final String QNONCE = "x-qys-nonce";
private static final String QSINA = "x-qys-signature";
/**
* 根据URL上传合同文档
*/
@Override
public String createbyfile (@RequestBody DianziFileReq dianziFileReq){
//获得得到文件的请求地址
String fileUrl = dianziFileReq.getFileUrl();
String title = dianziFileReq.getTitle();
String fileType = dianziFileReq.getFileType();
HttpURLConnection conn = null;
try{
URL path = new URL(fileUrl);
conn = (HttpURLConnection) path.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);
// 通过输入流获取数据
InputStream fis = conn.getInputStream();
byte[] buffer = readInputStream(fis);
ByteArrayResource byteArrayResource = new ByteArrayResource(buffer){
@Override
public String getFilename() {
//重写文件名称
return title;
}
};
MultiValueMap<String,Object> dataMap = new LinkedMultiValueMap<>();
dataMap.add("file",byteArrayResource);
dataMap.add("title",title);
dataMap.add("fileType",fileType);
//外部接口请求参数
String appToken = gatewayParams.getGateDianZiToken();
String appSecret = gatewayParams.getGateDianZiSecret();
Date nowDate = new Date();
Long timestamp = nowDate.getTime();
double nonce = Math.random();
String signature= MD5Utils.stringToMD5(appToken+appSecret+timestamp.toString()+nonce);
HttpHeaders headers = new HttpHeaders();
headers.set(QTKEN,appToken);
headers.set(QTIME,timestamp.toString());
headers.set(QNONCE,nonce+"");
headers.set(QSINA,signature);
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//外部接口的请求地址
String url =gatewayParams.getGateDianZiUrl() + "/v2/document/createbyfile";
HttpEntity<?> httpEntity = new HttpEntity<>(dataMap,headers);
RestTemplate restTemplate =new RestTemplate();
//请求外部接口地址
ResponseEntity<JSONObject> response =restTemplate.postForEntity(url,httpEntity, JSONObject.class);
Object result =response.getBody();
if(result != null){
Map<String,Object> resultMap = (Map<String, Object>) result;
Map<String,Object> resultMap1=(Map<String, Object>)resultMap.get("result");
//合同ID
return (String) resultMap1.get("documentId");
}else {
return "";
}
}catch (IOException ex){
ex.printStackTrace();
return ex.getMessage();
}
}
MD5Utils是一个MD5加密的方法,是外部接口请求头约定需要的。
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
public static String stringToMD5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(
plainText.getBytes()
);
}
catch (NoSuchAlgorithmException e){
throw new RuntimeException("没有这个md5算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for(int i = 0; i < 32 - md5code.length(); i++){
md5code = "0" + md5code;
}
return md5code;
}
}