對接Content-Type="application/x-www-form-urlencoded;"的接口示例

url:調用目標接口的路徑
headers:請求頭屬性
params:目標接口須要的入參
public static JSONObject doHttpPost(String url,Map<String, String> headers ,Map<String, String> params) {    // 建立Httpclient對象    CloseableHttpClient httpClient = null;    CloseableHttpResponse response = null;    String resultString = "";    try {        httpClient = HttpClients.createDefault();        // 建立Http Post請求        HttpPost httpPost = new HttpPost(url);        httpPost.setHeader("X-Gaia-Api-Key",headers.get("X-Gaia-Api-Key"));//網關key        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;");        // 建立參數列表        if (param != null) {            List<NameValuePair> paramList = new ArrayList<>();            for (String key : param.keySet()) {                paramList.add(new BasicNameValuePair(key, param.get(key)));            }            // 模擬表單            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");            httpPost.setEntity(entity);        }        // 執行http請求        response = httpClient.execute(httpPost);        resultString = EntityUtils.toString(response.getEntity(), "utf-8");    } catch (Exception e) {        log.error("HttpClientUtil/doPost,error:{}",e);    } finally {        try {            if (response != null) {                response.close();            }            if (httpClient != null) {                httpClient.close();            }        } catch (IOException e) {            log.error("HttpClientUtil/close,error:{}",e);        }    }    return JSON.parseObject(resultString);}
相關文章
相關標籤/搜索