对接的接口是MutipartFile的上传接口,后台用Http方式去调用,所以可以使用HttpClient或者用Spring框架封装的RestTemplate去后台http请求
要对接的接口:
@PostMapping("api/attachment/upload")
public ResultBean<String> upload(MultipartFile file) throws IOException {
attachmentService.upload(file);
return ResultBean.ok();
}
post调用,post接口,都是在body里传参,这里使用form-data
- 方法:RestTemplate加上FileSystemResource转一下,然后传参
后台http调用,用FileSystemResource
转一下,直接用RestTemplate
@Test
public void test() {
RestTemplate restTemplate = new RestTemplate();
FileSystemResource resource = new FileSystemResource(new File("D:\\test.txt"));
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
param.add("fileName", "test.txt");
Object object = restTemplate.postForObject("http://127.0.0.1:8101/api/attachment/upload", param, Object.class);
System.out.println(object.toString());
}
2、HttpClient框架,需要MultipartEntityBuilder 进行封装
<!--httpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.9</version>
</dependency>
HttpClient工具类:
package com.example.gateway.demo.util;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpUtil {
/**
* 默认参数设置
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
* setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
*/
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();
public static String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpEntity entity = null;
String responseContent = null;
try {
// 创建默认的httpClient实例
httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig);
// 执行请求
long execStart = System.currentTimeMillis();
response = httpClient.execute(httpPost);
long execEnd = System.currentTimeMillis();
System.out.println("post请求耗时:" + (execEnd - execStart) + "ms");
long getStart = System.currentTimeMillis();
entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
long getEnd = System.currentTimeMillis();
System.out.println("获取响应结果耗时:" + (getEnd - getStart) + "ms");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}
}
package com.example.gateway.demo;
import com.example.gateway.demo.util.HttpUtil;
import com.example.gateway.demo.util.Sm3Util;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
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.entity.mime.content.FileBody;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class DemoApplication {
public static void main(String[] args) {
System.out.println(doPostRequest());
}
private static void setHttpHeader(HttpPost httpPost) throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
String appid = "appid";
String apiname = "apiname";
String appkey = "appkey";
// 生成签名
String key = appkey.replaceAll("-", "");
String timestamp = String.valueOf ((System.currentTimeMillis() / 1000)) ;
String stringtosign = appid+ apiname + timestamp;
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] bytes = cipher.doFinal(stringtosign.getBytes("utf-8"));
String encryptedData = new Base64().encodeToString(bytes);
httpPost.setHeader("apiname",apiname);
httpPost.setHeader("appid",appid);
httpPost.setHeader("signature",encryptedData);
httpPost.setHeader("Cache-Control", "no-cache");
}
private static String doPostRequest() {
File file = new File("D://test.txt");
FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA, file.getName());
String httpUrl = "http://127.0.0.1:8101/api/upload";
// 创建httpPost
HttpPost httpPost = new HttpPost(httpUrl);
// 创建参数队列
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("utf-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.MULTIPART_FORM_DATA);
builder.addPart("file", fileBody);
HttpEntity httpEntity = builder.build();
try {
httpPost.setEntity(httpEntity);
setHttpHeader(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
String result = HttpUtil.sendHttpPost(httpPost);
return result;
}
}
本文同步分享在 博客“smileNicky”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。