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

 

 

 

 

好未來創業


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM