对接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);}
相关文章
相关标签/搜索