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 @   王广福  阅读(884)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示