您好,欢迎来到星星旅游。
搜索
您的当前位置:首页Java代码:CloseableHttpClient HttpPost 调用外部接口(模拟表单传参或JSON传参)

Java代码:CloseableHttpClient HttpPost 调用外部接口(模拟表单传参或JSON传参)

来源:星星旅游
public void finishNotice(String url ,Map<String, String> paraMap){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        Integer status=null;
        String msg="";
        String problemCode="";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");            
// 创建参数列表
            if (paraMap != null) {
//                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : paraMap.keySet()) {
//                    paramList.add(new BasicNameValuePair(key, paraMap.get(key)));
                    if(key.equals("problemCode")){
                        problemCode = paraMap.get(key);
                    }
                }
                // 模拟表单
//                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
//                httpPost.setEntity(entity);
                //json格式传参
                String param=JSON.toJSONString(paraMap);
                httpPost.setEntity(new StringEntity(param));
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject jsonObject = JSON.parseObject(resultString);
            status = (Integer) jsonObject.get("status");
            msg= (String) jsonObject.get("msg");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- stra.cn 版权所有 赣ICP备2024042791号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务