HTTPClients使用

一. 创建httpclient对象用于发送get、post等请求
1. HttpClients.custom()的方式--自定义httpclient对象,多用于含有cookie的请求
1. CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("session","true");
cookie.setDomain("127.0.0.1");
cookie.setPath("/");
cookieStore.addCookie(cookie);
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
2. HttpClients.createDefault()的方式--默认httpclient方式
CloseableHttpClient httpClient = HttpClients.createDefault();
二. 创建请求对象
1. Get请求:HttpGet get= new HttpGet("http://127.0.0.1:8899/getNoparams");
2. Post请求:HttpPost post = new HttpPost("http://127.0.0.1:8899/postNoparams");
3. 设置请求数据
1. form表单格式(Bean对象转Map,遍历Map添加到List集合中)
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("name","zhangsan");
hashMap.put("age","18");
List<NameValuePair> list = new ArrayList<NameValuePair>();
Set<Map.Entry<String, String>> entries = hashMap.entrySet();
for(Map.Entry<String, String> entry:entries){
list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
post.setEntity(new UrlEncodedFormEntity(list,"utf-8"));
2. json格式(Bean对象转JSON字符串)
1. User user = new User();
user.setName("zhangsan");
user.setAge("18");
String json = JSONObject.toJSON(user).toString();
post.setEntity(new StringEntity(json));
三. 发送请求 返回值类型为CloseableHttpResponse
CloseableHttpResponse response = httpclient.execute(post)
CloseableHttpResponse response = httpclient.execute(get)
四. 返回值转为字符串
String data = EntityUtils.toString(response.getEntity());

posted @ 2022-07-26 10:16  王广福  阅读(959)  评论(0)    收藏  举报