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

举报
yd_273762914 发表于 2022/04/30 22:31:45 2022/04/30
【摘要】 对接的接口是MutipartFile的上传接口,后台用Http方式去调用,所以可以使用HttpClient或者用Spring框架封装的RestTemplate去后台http请求 要对接的接口: @Po...

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

要对接的接口:

@PostMapping("api/attachment/upload")
    public ResultBean<String> upload(MultipartFile file) throws IOException {
        attachmentService.upload(file);
        return ResultBean.ok();
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5

post调用,post接口,都是在body里传参,这里使用form-data
在这里插入图片描述

  1. 方法: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());
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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;
    }

}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
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;
    }


}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

文章来源: smilenicky.blog.csdn.net,作者:smileNicky,版权归原作者所有,如需转载,请联系作者。

原文链接:smilenicky.blog.csdn.net/article/details/124470026

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。