http使用formData方式傳輸文件請求


轉載請注明出處:

  項目中有遇到http使用formData請求傳輸文件,在此記錄一下

1.依賴jar包:

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
    </dependency>

2.代碼:

// 定義httpClient和response
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();;
        CloseableHttpResponse response = null;
        try {
            // 定義Post請求
            HttpPost httpPost = new HttpPost(uri);
            // 設置配置
            Builder builder = createBuilder();
            RequestConfig config = null;
            // 是否開啟代理模式訪問
            if (enabled) {
                HttpHost proxy = new HttpHost(host, port, Proxy.Type.HTTP.toString());
                config = builder.setProxy(proxy).build();
            } else {
                config = builder.build();
            }
            httpPost.setConfig(config);
            // 設置請求頭
           // httpPost.setHeader(FucdnStrConstant.ACCEPT.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE);
            httpPost.setHeader(FucdnStrConstant.CONTENT_TYPE.getConstant(), MediaType.MULTIPART_FORM_DATA_VALUE);
            // 發送請求得到返回數據
            httpPost.setEntity(fileBuilder.build());
            // 得到響應
            response = httpClient.execute(httpPost);
            // 狀態碼
           int statusCode = response.getStatusLine().getStatusCode();
            // 響應內容
            HttpEntity entity = response.getEntity();
            // 響應內容
            String responseContent = EntityUtils.toString(entity);
        } catch (Exception e) {
            throw new FucdnException(e);
        } finally {
            // 關閉流
            Utils.closeStream(response);
            Utils.closeStream(httpClient);
        }

  

   

 private Builder createBuilder() {
            // init Builder and init TIME_OUT
            return RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000)
                    .setConnectionRequestTimeout(20000);
        }
    
    
 public static void closeStream(Closeable c) {
            // 流不為空
            if (c != null) {
                try {
                    // 流關閉
                    c.close();
                } catch (IOException ex) {
                    LOGGER.error("closeStream failed", ex);
                }
            }
    }

 

 
        


免責聲明!

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



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