Apache HttpClient的实例CloseableHttpClient发起Http请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y532798113/article/details/82227677

public static String doPost(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    Object value =  param.get(key);
                    if(value!=null){
                        paramList.add(new BasicNameValuePair(key,value+""));
                    }
                }
                // 模拟表单
                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) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println(resultString);
        return resultString;
    }

猜你喜欢

转载自blog.csdn.net/y532798113/article/details/82227677