使用HttpClients发送http请求

public String xxxx(String cc,String cid) throws Exception{
   String resultData = "";
   // 创建httppost对象
   HttpPost post = null;
   //创建httpclient对象
   CloseableHttpClient client = HttpClients.createDefault();
   String url = "http://xxxx/xxxx";
   // 创建uri
   post = new HttpPost(url);
   //设置Header
   post.setHeader("Content-Type", "application/json");
   post.setHeader("Accept", "application/json");
   // 构建消息实体
   JSONObject jsonObj = new JSONObject();
   jsonObj.put("id", "33");
   jsonObj.put("key", "");
   jsonObj.put("cc",cc);
   jsonObj.put("cid", cid);
   StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
   entity.setContentEncoding("UTF-8");
   // 发送Json格式的数据请求
   entity.setContentType("application/json");
   post.setEntity(entity);
   CloseableHttpResponse response = client.execute(post);
   //获取结果实体
   HttpEntity results = response.getEntity();
   String string = "";
   if (results != null) {
    //按指定编码转换结果实体为String类型
    string = EntityUtils.toString(results, "UTF-8");
    }
   JSONObject jsonObject = JSONObject.fromObject(string);
   if (jsonObject.getString("success").equals("true")) 
         resultData = "测试成功!" ;
     logger.info("测试成功!");
   } else {
     resultData = "测试失败!" ;
    logger.error("测试失败!");
   }
   //释放
   EntityUtils.consume(entity);
   //释放链接
   response.close();
   return resultData;
}

你可能感兴趣的:(使用HttpClients发送http请求)