java post請求form表單格式發送數據,ContentType=multipart/form-data


 /**
     * post請求form表單格式發送數據
     *  multipart/form-data
     * @param url 接口地址
     * @param param 參數數組
     * @return 返回結果
     * @throws IOException
     */
    public static String sendPost(String url, Map<String, String> param) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httppost = new HttpPost(url);
            //構建超時等配置信息
            RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //連接超時時間
                    .setConnectionRequestTimeout(1000) //從連接池中取的連接的最長時間
                    .setSocketTimeout(10 * 1000) //數據傳輸的超時時間
                    .build();
            httppost.setConfig(config);
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            ContentType strContent = ContentType.create("text/plain", Charset.forName("UTF-8"));
            //參數填充
            for (String key : param.keySet()) {
                entityBuilder.addTextBody(key, param.get(key),strContent);
            }
            HttpEntity entity = entityBuilder.build();
            httppost.setEntity(entity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                //回復接收
                result = EntityUtils.toString(resEntity, "UTF-8");
            } finally {
                response.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {
            httpclient.close();
        }
        return result;
    }

  


免責聲明!

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



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