java 后台請求其他接口轉發文件


轉載: https://blog.csdn.net/lsqingfeng/article/details/90611686

我這里的需求主要是因為https頁面要訪問http,不能直接訪問,暫時加一層的方法訪問.

上傳文件先請求https,然后在https的后台訪問http

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.3</version>
</dependency>
/**
     * 使用httpclint 發送文件
     * @param url: 接口全路徑
     * @param file: 上傳文件
     * @param fileParamName: 接口對應文件的參數名:相當於@RequestParam("fileParamName")
     * @param headerParams: 請求頭信息: 可能需要攜帶token,注意不要設置content-type
     * @param otherParams: 其他參數
     * @return
     */
    public static String uploadApiFile(String url ,MultipartFile file,String fileParamName,Map<String,String>headerParams,Map<String,String>otherParams) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            //添加header
            for (Map.Entry<String, String> e : headerParams.entrySet()) {
                httpPost.addHeader(e.getKey(), e.getValue());
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代碼解決返回中文亂碼問題
            builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                builder.addTextBody(e.getKey(), e.getValue());// 類似瀏覽器表單提交,對應input的name和value
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 執行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 將響應內容轉換為字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

如果有大佬知道js 直接https網頁訪問http上傳文件的方式! 還望指點一二


免責聲明!

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



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