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

轉載請註明出處:apache

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

1.依賴jar包:spa

    <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);
                }
            }
    }
相關文章
相關標籤/搜索