• feign及(httpclient基于https)协议文件上传、下载到文件服务器


    功能描述:上传文件到文件服务器,返回文件在服务器地址,下载(获取)文件直接可以在浏览器拼接地址(ip:端口/返回文件在服务器地址)

    一、feign上传下载

    引入maven依赖

    1. org.springframework.boot
    2. spring-boot-starter-web
    3. org.springframework.cloud
    4. spring-cloud-starter-openfeign

    1、上传接口

    1. @FeignClient(name = "fileUploadAPI", url = "${file.uploadPath}")
    2. public interface FileUploadAPI {
    3. @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    4. String uploadImage(@RequestPart(value = "img") MultipartFile img);
    5. }

    2、下载接口

    1. @FeignClient(name = "FileDownAPI",url = "${file.downPath}")
    2. public interface FileDownAPI {
    3. @GetMapping(value = "{path}")
    4. Response getImage(@PathVariable("path") String path);
    5. }

    下载文件api调用 

    1. private void downImage(String path, String parentFile) {
    2. Response response = fileDownAPI.getImage(path);
    3. Response.Body body = response.body();
    4. try {
    5. InputStream inputStream = body.asInputStream();
    6. BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    7. //路劲类似格式:/images/20220719/6204bc93415ec044c50f60ad5bcc132c.png
    8. String[] split = path.split("\\/");
    9. if (split.length == 4) {
    10. File img = new File(parentFile + "/" + split[3]);
    11. if (!img.exists()) {
    12. img.createNewFile();
    13. }
    14. FileOutputStream fileOutputStream = new FileOutputStream(img);
    15. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    16. int length = 0;
    17. byte[] bytes = new byte[1024 * 10];
    18. while ((length = bufferedInputStream.read(bytes)) != -1) {
    19. bufferedOutputStream.write(bytes, 0, length);
    20. }
    21. bufferedOutputStream.flush();
    22. bufferedOutputStream.close();
    23. bufferedInputStream.close();
    24. inputStream.close();
    25. } else {
    26. throw new RuntimeException("图片路径格式不对,必须为:/***/***/**.jpg 格式");
    27. }
    28. } catch (IOException e) {
    29. logger.error(e.getMessage());
    30. throw new RuntimeException("获取文件失败", e);
    31. }
    32. }

    这里之所以写两个接口是因为如果上传地址和下载地址不一致(端口开始就不一样)的情况

    二、httpclient上传

    1、http协议文件上传

    1. private static String inputFileByHttp(String uploadUrl) throws IOException {
    2. // uploadUrl = "http://192.168.0.1:8080/images";
    3. String localFile = "docs/test.txt";
    4. File file = new File(localFile);
    5. CloseableHttpClient httpClient = HttpClients.createDefault();
    6. HttpPost post = new HttpPost(uploadUrl);
    7. MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    8. multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
    9. //这两个都可以
    10. // multipartEntityBuilder.addBinaryBody("img",fileInputStream,ContentType.MULTIPART_FORM_DATA,"test.txt");
    11. multipartEntityBuilder.addBinaryBody("img", file);
    12. HttpEntity httpEntity = multipartEntityBuilder.build();
    13. post.setEntity(httpEntity);
    14. CloseableHttpResponse response = httpClient.execute(post);
    15. String result = "无数据返回";
    16. if (200 == response.getStatusLine().getStatusCode()) {
    17. HttpEntity entity = response.getEntity();
    18. if (null != entity) {
    19. result = EntityUtils.toString(entity, "UTF-8");
    20. }
    21. System.out.println(result);
    22. }
    23. return result;
    24. }

    2、https协议文件上传

    1. private static String inputFileByHttps(String uploadUrl) throws IOException {
    2. // uploadUrl = "https://baidu.xx.com:10000/images";
    3. String localFile = "docs/test.txt";
    4. File file = new File(localFile);
    5. FileInputStream fileInputStream = new FileInputStream(file);
    6. CloseableHttpClient httpClient = createSSLClient();
    7. HttpPost post = new HttpPost(uploadUrl);
    8. MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    9. multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
    10. //这两个都可以
    11. multipartEntityBuilder.addBinaryBody("img",fileInputStream,ContentType.MULTIPART_FORM_DATA,"test.txt");
    12. // multipartEntityBuilder.addBinaryBody("img", file);
    13. HttpEntity httpEntity = multipartEntityBuilder.build();
    14. post.setEntity(httpEntity);
    15. CloseableHttpResponse response = httpClient.execute(post);
    16. String result = "无数据返回";
    17. if (200 == response.getStatusLine().getStatusCode()) {
    18. HttpEntity entity = response.getEntity();
    19. if (null != entity) {
    20. result = EntityUtils.toString(entity, "UTF-8");
    21. }
    22. System.out.println(result);
    23. }
    24. return result;
    25. }
    26. private static CloseableHttpClient createSSLClient() {
    27. SSLContext sslContext;
    28. try {
    29. sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
    30. //信任所有
    31. @Override
    32. public boolean isTrusted(X509Certificate[] xcs, String string) {
    33. return true;
    34. }
    35. }).build();
    36. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    37. return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    38. } catch (KeyStoreException ex) {
    39. ex.printStackTrace();
    40. } catch (NoSuchAlgorithmException ex) {
    41. ex.printStackTrace();
    42. } catch (KeyManagementException ex) {
    43. ex.printStackTrace();
    44. }
    45. return HttpClients.createDefault();
    46. }

    http和https综上代码可以看到在获取httpclient的时候有区别,https需要设置ssl信任

    三、postman上面测试https协议文件上传设置

     文件key必须要正确

    关闭settings设置里面的ssl证书验证,一般默认是开启的 

     

     开启settings设置里面的CA证书,默认是关闭的

  • 相关阅读:
    H5微信端在IOS上不能播放音乐解决方案
    基于Python和TensorFlow实现BERT模型应用
    [AHK V2]SQLite测试用例
    35岁农村小伙的成长之路,从小白程序员到大厂高级技术专家
    flutter ios Exception : No Impeller Context is Available
    linux 使用 squid
    Synchronized关键字使用不合理,导致的多线程下线程阻塞问题排查
    小文件写入性能 5 倍于 S3FS,JuiceFS 加速生信研究
    网络安全漏洞分析与漏洞复现
    LeetCode220807_73、旋转图像
  • 原文地址:https://blog.csdn.net/yang1076180972/article/details/125992332