zoukankan      html  css  js  c++  java
  • Java后端模拟前端请求

    在知道源文件目录的情况下,直接在后端执行上传

    package com.example.hystrix.controller;
    
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import java.io.File;
    
    public class Demo{
    
        public void uploadTest() {
    
            String url = "http://localhost:8080/upload"; //上传的地址
            String filePath = "D:/test/test.mp4";
    
            RestTemplate rest = new RestTemplate();
            FileSystemResource resource = new FileSystemResource(new File(filePath));
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource); //MultipartFile的名称
            String restResult = rest.postForObject(url, param, String.class);
            System.out.println(restResult);
        }
    }

    另一种方式,代码片段:

              MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
                    FileSystemResource resource = new FileSystemResource(new File(filePath));
                    param.add("file", resource);
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, headers);
                    RestTemplate rest = new RestTemplate();
                    String restResult = rest.postForObject(url, requestEntity, String.class);

     ---------------------------------------------

    发现一个问题,/download这个POST接口,@QueryParam这个注解虽然是post请求但是不会以body里的内容传参,而是用parameter传参,也就是get请求的传参方式

    我的请求路径是:http://127.0.0.1:8080//rest/inner/attachment/download?attachmentId=c02f19a4-94c7-11ea-b9d6-000c29f9ae6a

    使用RestTemplate.postForObject无法调用,报错:Only resource methods using @FormParam will work as expected

        @POST
        @Path("/download")
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
        public Response download(@QueryParam("attachmentId") String attachmentId, @Context HttpServletResponse response) {
    
    }

     所以我改用httpclient,调用POST成功

    /**
         * @param url
         *            下载路径
         * @param downloadDir
         *            下载存放目录
         */
        public static void downloadFile(String url, String downloadDir) {
            File file = new File(downloadDir);
            if (!file.exists()) { // 如果文件不存在则下载
                CloseableHttpClient httpclient = HttpClients.createDefault();
                try {
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.addHeader("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
                    CloseableHttpResponse response = httpclient.execute(httpPost);
                    try {
                        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                            HttpEntity entity = response.getEntity();
                            if (entity != null) {
                                InputStream in = entity.getContent();
                                OutputStream out = new FileOutputStream(file);
                                int size = 0;
                                int lent = 0;
                                byte[] buf = new byte[1024];
                                while ((size = in.read(buf)) != -1) {
                                    lent += size;
                                    out.write(buf, 0, size);
                                }
                                in.close();
                                out.close();
                            }
                            EntityUtils.consume(entity);
                        } else {
                            logger.error("文件下载失败" + url);
                        }
                    } finally {
                        response.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        httpclient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    好未来创业

  • 相关阅读:
    ezjailserver备份和恢复方法
    三种方式上传文件-Java
    将EBS设为首页worklist删除误报
    软软测试总结检查
    C++包括头文件&lt;&gt;和&quot;&quot;差额
    web报告工具FineReport在使用方法和解决方案常见错误遇到(一)
    WEB流程设计器 = jQuery + jsPlumb + Bootstrap
    SuperMap/PlottingSymbol
    基于easyui开发Web版Activiti流程定制器详解(六)——Draw2d的扩展(三)
    基于easyui开发Web版Activiti流程定制器详解(六)——Draw2d详解(二)
  • 原文地址:https://www.cnblogs.com/Alwaysbecoding/p/12877950.html
Copyright © 2011-2022 走看看