Http接口Post方式传送File文件示例

您所在的位置:网站首页 api接口传输方式 Http接口Post方式传送File文件示例

Http接口Post方式传送File文件示例

2023-10-02 03:34| 来源: 网络整理| 查看: 265

对接的接口是MutipartFile的上传接口,后台用Http方式去调用,所以可以使用HttpClient或者用Spring框架封装的RestTemplate去后台http请求

要对接的接口:

@PostMapping("api/attachment/upload") public ResultBean 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 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 进行封装

org.apache.httpcomponents httpclient 4.5.9 org.apache.httpcomponents httpmime 4.5.9

HttpClient工具类:

package com.example.gateway.demo.util; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.clienthods.CloseableHttpResponse; import org.apache.http.clienthods.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.clienthods.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; } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3