发送POST请求(HTTP),K-V形式

/**
     * 发送POST请求(HTTP),K-V形式
     * @param url
     * @param params
     * @author Charlie.chen
     * @return
     */
    public static String doPost(String url, Map<string, string=""> params) {
 
        // 创建默认的HttpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
 
            // 定义一个get请求方法
            HttpPost httppost = new HttpPost(url);
 
            // List<namevaluepair> parameters = new ArrayList<namevaluepair>();
            // parameters.add(new BasicNameValuePair("username", userName));
            // parameters.add(new BasicNameValuePair("password", password));
 
            // 定义post请求的参数
            // 建立一个NameValuePair数组,用于存储欲传送的参数
            List<namevaluepair> list = new ArrayList<namevaluepair>();
            Iterator iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<string, string=""> elem = (Entry<string, string="">) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
            }
            if (list.size() > 0) {
                httppost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
            }
 
 
            // httppost.setHeader("Content-type","application/json,charset=utf-8");
            // httppost.setHeader("Accept", "application/json");
 
 
            // 执行post请求,返回response服务器响应对象, 其中包含了状态信息和服务器返回的数据
            CloseableHttpResponse httpResponse = httpclient.execute(httppost);
 
            // 使用响应对象, 获得状态码, 处理内容
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 使用响应对象获取响应实体
                HttpEntity entity = httpResponse.getEntity();
                // 将响应实体转为字符串
                String response = EntityUtils.toString(entity, "utf-8");
                return response;
 
            } else {
                // log.error("访问失败"+statusCode);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接, 和释放资源
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
 
 
转载:https://www.2cto.com/kf/201611/561147.html
posted @ 2018-04-03 14:59  盟约  阅读(1557)  评论(0编辑  收藏  举报