文件與其餘參數一塊兒上傳

對接方提供的接口樣例以下

實現代碼以下  java

public static String doPostUploadFile(String url, MultipartFile file,Map<String, Object> params){
    log.info("請求地址:" + url);
    log.info("請求參數:" + params);
    String resultStr = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    String filename=file.getOriginalFilename();
    try {
        builder.addBinaryBody("file",file.getInputStream(), ContentType.DEFAULT_BINARY, filename);
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if(entry.getValue() == null)
                continue;
            builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
        }
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);

        // 設置鏈接超時時間
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout).setSocketTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);
        HttpEntity responseEntity = response.getEntity();
        int code = response.getStatusLine().getStatusCode();
        if (responseEntity != null) {
            // 將響應內容轉換爲字符串
            resultStr = EntityUtils.toString(responseEntity, java.nio.charset.Charset.forName("UTF-8"));
            log.info("返回值:"+resultStr);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return resultStr;
}
相關文章
相關標籤/搜索