发送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

转载于:https://www.cnblogs.com/huameitang/p/8708519.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值