httpclient框架中,不同数据格式的情况下执行client的方法

1.application/json

拼接出来的body本质是一串Sring,所以可以用StringEntity,使用方法如下:

//构造测试数据
JSONObject param = new JSONObject();
param.put("key","value");
//定义HttpClient
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.application/x-www-form-urlencoded

拼接出来的数据格式是 key1=value1&key2=value2的格式,所以使用List来装测试数据,对应httpclient中的方法应该用UrlEncodedFormEntity,使用方法如下:

//构造测试数据
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(); 

猜你喜欢

转载自blog.csdn.net/lt326030434/article/details/81067333