• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

HttpClient发送Post请求StringEntity 和 UrlEncodedFormEntity

武飞扬头像
m0_37346206
帮助1

1.StringEntity

StringEntity有两个参数,一个是具体的参数值(string串),另一个是ContentType,默认是text/plain,编码格式是:ISO_5598_1。

使用httpclient时,尽量指定编码方式来初始化StringEntity。

使用HttpClient来发送请求获取数据:拼接出来的body本质是一串Sring,所以可以用StringEntity,使用方法如下:

  1.  
    //构造测试数据
  2.  
    JSONObject param = new JSONObject();
  3.  
    param.put("key","value");
  4.  
    //CloseableHttpClient:建立一个可以关闭的httpClient
  5.  
    //这样使得创建出来的HTTP实体,可以被Java虚拟机回收掉,不至于出现一直占用资源的情况。
  6.  
    CloseableHttpClient client = HttpClients.createDefault();
  7.  
    //创建post请求
  8.  
    HttpPost post = new HttpPost(testUrl);
  9.  
    //生成装载param的entity
  10.  
    StringEntity entity = new StringEntity(param.toString(), "utf-8");
  11.  
    post.setEntity(entity);
  12.  
    //执行请求
  13.  
    CloseableHttpResponse response = TestConfig.httpClient.execute(post);
  14.  
    //返回string格式的结果
  15.  
    String result = EntityUtils.toString(response.getEntity(), "utf-8");
  16.  
    //关闭链接
  17.  
    post.releaseConnection();
  18.  
    client.close();
学新通

2.UrlEncodedFormEntity

ContentType就是application/x-www-form-urlencoded,urlEncodeFormEntity会将参数以key1=value1&key2=value2的键值对形式发出。类似于传统的application/x-www-form-urlencoded表单上传。

  1.  
    //构造测试数据
  2.  
    List<NameValuePair> param = new ArrayList<NameValuePair>();
  3.  
    param.add(new BasicNameValuePair("key1","value1"));
  4.  
    param.add(new BasicNameValuePair("key2","value2"));
  5.  
    //定义HttpClient
  6.  
    CloseableHttpClient client = HttpClients.createDefault();
  7.  
    //创建post请求
  8.  
    HttpPost post = new HttpPost(testUrl);
  9.  
    //生成装载param的entity
  10.  
    HttpEntity entity = new UrlEncodedFormEntity(param, "utf-8");
  11.  
    post.setEntity(entity);
  12.  
    //执行请求
  13.  
    CloseableHttpResponse response = client.execute(post);
  14.  
    //返回string格式的结果
  15.  
    String result = EntityUtils.toString(response.getEntity(), "utf-8");
  16.  
    //关闭链接
  17.  
    post.releaseConnection();
  18.  
    client.close();
学新通

StringEntity可以用来灵活设定参数格式形式,而UrlEncodeFormEntity则适合于传统表单格式的参数形式。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeggie
系列文章
更多 icon
同类精品
更多 icon
继续加载