Java开发小技巧(五):HttpClient工具类
程序员文章站
2022-05-07 17:01:51
大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具有访问HTTP协议基本功能的高效工具类,为后续开发使用提供方便。 ......
前言
大多数java应用程序都会通过http协议来调用接口访问各种网络资源,jdk也提供了相应的http工具包,但是使用起来不够方便灵活,所以我们可以利用apache的httpclient来封装一个具有访问http协议基本功能的高效工具类,为后续开发使用提供方便。
文章要点:
- httpclient使用流程
- 工具类封装
- 使用实例
httpclient使用流程
1、导入maven依赖
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5.5</version> </dependency> <dependency> <groupid>commons-codec</groupid> <artifactid>commons-codec</artifactid> <version>1.11</version> </dependency> <dependency> <groupid>com.google.code.gson</groupid> <artifactid>gson</artifactid> <version>2.8.5</version> </dependency>
2、创建httpclient实例
httpclient client = httpclientbuilder.create().build();
3、创建请求方法的实例
get请求使用httpget,post请求使用httppost,并传入请求的url
// post请求 httppost post = new httppost(url); // get请求,url中带请求参数 httpget get = new httpget(url);
4、添加请求参数
普通形式
list<namevaluepair> list = new arraylist<>(); list.add(new basicnamevaluepair("username", "admin")); list.add(new basicnamevaluepair("password", "123456")); // get请求方式 // 由于get请求的参数是拼装在url后方,所以需要构建一个完整的url,再创建httpget实例 uribuilder uribuilder = new uribuilder("http://www.baidu.com"); uribuilder.setparameters(list); httpget get = new httpget(uribuilder.build()); // post请求方式 post.setentity(new urlencodedformentity(list, charsets.utf_8));
json形式
map<string,string> map = new hashmap<>(); map.put("username", "admin"); map.put("password", "123456"); gson gson = new gson(); string json = gson.tojson(map, new typetoken<map<string, string>>() {}.gettype()); post.setentity(new stringentity(json, charsets.utf_8)); post.addheader("content-type", "application/json");
5、发送请求
调用httpclient实例的execute方法发送请求,返回一个httpresponse对象
httpresponse response = client.execute(post);
6、获取结果
string result = entityutils.tostring(response.getentity());
7、释放连接
post.releaseconnection();
工具类封装
httpclient工具类代码(根据相应使用场景进行封装):
public class httpclientutil { // 发送get请求 public static string getrequest(string path, list<namevaluepair> parametersbody) throws restapiexception, urisyntaxexception { uribuilder uribuilder = new uribuilder(path); uribuilder.setparameters(parametersbody); httpget get = new httpget(uribuilder.build()); httpclient client = httpclientbuilder.create().build(); try { httpresponse response = client.execute(get); int code = response.getstatusline().getstatuscode(); if (code >= 400) throw new runtimeexception((new stringbuilder()).append("could not access protected resource. server returned http code: ").append(code).tostring()); return entityutils.tostring(response.getentity()); } catch (clientprotocolexception e) { throw new restapiexception("postrequest -- client protocol exception!", e); } catch (ioexception e) { throw new restapiexception("postrequest -- io error!", e); } finally { get.releaseconnection(); } } // 发送post请求(普通表单形式) public static string postform(string path, list<namevaluepair> parametersbody) throws restapiexception { httpentity entity = new urlencodedformentity(parametersbody, charsets.utf_8); return postrequest(path, "application/x-www-form-urlencoded", entity); } // 发送post请求(json形式) public static string postjson(string path, string json) throws restapiexception { stringentity entity = new stringentity(json, charsets.utf_8); return postrequest(path, "application/json", entity); } // 发送post请求 public static string postrequest(string path, string mediatype, httpentity entity) throws restapiexception { logger.debug("[postrequest] resourceurl: {}", path); httppost post = new httppost(path); post.addheader("content-type", mediatype); post.addheader("accept", "application/json"); post.setentity(entity); try { httpclient client = httpclientbuilder.create().build(); httpresponse response = client.execute(post); int code = response.getstatusline().getstatuscode(); if (code >= 400) throw new restapiexception(entityutils.tostring(response.getentity())); return entityutils.tostring(response.getentity()); } catch (clientprotocolexception e) { throw new restapiexception("postrequest -- client protocol exception!", e); } catch (ioexception e) { throw new restapiexception("postrequest -- io error!", e); } finally { post.releaseconnection(); } } }
使用实例
get请求
list<namevaluepair> parametersbody = new arraylist(); parametersbody.add(new basicnamevaluepair("userid", "admin")); string result = httpclientutil.getrequest("http://www.test.com/user",parametersbody);
post请求
list<namevaluepair> parametersbody = new arraylist(); parametersbody.add(new basicnamevaluepair("username", "admin")); parametersbody.add(new basicnamevaluepair("password", "123456")); string result = httpclientutil.postform("http://www.test.com/login",parametersbody);
post请求(json形式)
map<string,string> map = new hashmap<>(); map.put("username", "admin"); map.put("password", "123456"); gson gson = new gson(); string json = gson.tojson(map, new typetoken<map<string, string>>() {}.gettype()); string result = httpclientutil.postjson("http://www.test.com/login", json);
关于httpclient的详细介绍看这里:httpclient入门
本文为作者kmacro原创,转载请注明来源:。
上一篇: 新鲜鲍鱼怎么做好吃又简单而且营养还高!