1.StringEntity
StringEntity有两个参数,一个是具体的参数值(string串),另一个是ContentType,默认是text/plain,编码格式是:ISO_5598_1。
使用httpclient时,尽量指定编码方式来初始化StringEntity。
使用HttpClient来发送请求获取数据:拼接出来的body本质是一串Sring,所以可以用StringEntity,使用方法如下:
//构造测试数据
JSONObject param = new JSONObject();
param.put("key","value");
//CloseableHttpClient:建立一个可以关闭的httpClient
//这样使得创建出来的HTTP实体,可以被Java虚拟机回收掉,不至于出现一直占用资源的情况。
CloseableHttpClient client = HttpClients.createDefault();
//创建post请求
HttpPost post = new HttpPost(testUrl);
//生成装载param的entity
StringEntity entity = new StringEntity(param.toString(), "utf-8");
post.setEntity(entity);
//执行请求
CloseableHttpResponse response = TestConfig.httpClient.execute(post);
//返回string格式的结果
String result = EntityUtils.toString(response.getEntity(), "utf-8");
//关闭链接
post.releaseConnection();
client.close();
2.UrlEncodedFormEntity
ContentType就是application/x-www-form-urlencoded,urlEncodeFormEntity会将参数以key1=value1&key2=value2的键值对形式发出。类似于传统的application/x-www-form-urlencoded表单上传。
//构造测试数据
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("key1","value1"));
param.add(new BasicNameValuePair("key2","value2"));
//定义HttpClient
CloseableHttpClient client = HttpClients.createDefault();
//创建post请求
HttpPost post = new HttpPost(testUrl);
//生成装载param的entity
HttpEntity entity = new UrlEncodedFormEntity(param, "utf-8");
post.setEntity(entity);
//执行请求
CloseableHttpResponse response = client.execute(post);
//返回string格式的结果
String result = EntityUtils.toString(response.getEntity(), "utf-8");
//关闭链接
post.releaseConnection();
client.close();
StringEntity可以用来灵活设定参数格式形式,而UrlEncodeFormEntity则适合于传统表单格式的参数形式。