您现在的位置是:首页 > 文章详情

🔥 Solon 3.0 新特性:HttpUtils 了解一下

日期:2024-10-15点击:105

Solon 3.0 引入一个叫 HttpUtils 小插件,这是一个简单的同步 HTTP 客户端,基于 URLConnection 适配(也支持切换为 OkHttp 适配)。使得编写 HTTP 客户端代码更加直观和易于阅读。

  • 使用 URLConnection 适配时(大小为 40KB 左右)。默认
  • 使用 OkHttp 适配时(大小为 3.1MB 左右)。当引入 okhttp 包时,自动切换为 okhttp 适配。

一、请求操作

  • HEAD 请求并返回 status code
 int code = HttpUtils.http("http://localhost:8080/hello").head(); 
  • GET 请求并返回 body string
 String body = HttpUtils.http("http://localhost:8080/hello").get(); 
  • GET 请求并返回 body as bean
 //for Bean Book book = HttpUtils.http("http://localhost:8080/book?bookId=1") .getAs(Book.class); 

二、提交操作

PUT、PATCH、DELETE 数据提交,与 POST 相同。

  • POST 请求并返回 body stirng (x-www-form-urlencoded)
 //x-www-form-urlencoded String body = HttpUtils.http("http://localhost:8080/hello") .data("name","world") .post(); 
  • POST 请求并返回 body stirng (form-data)
 //form-data String body = HttpUtils.http("http://localhost:8080/hello") .data("name","world") .post(true); // useMultipart //form-data :: upload-file String body = HttpUtils.http("http://localhost:8080/hello") .data("name", new File("/data/demo.jpg")) .post(true); // useMultipart 
  • POST 请求并返回 body stirng (body-raw)
 //body-json String body = HttpUtils.http("http://localhost:8080/hello") .bodyOfJson("{\"name\":\"world\"}") .post(); 
  • POST 请求并返回 body as bean (body-raw)
 //for Bean Result body = HttpUtils.http("http://localhost:8080/book") .bodyOfBean(book) //会通过 serializer 指定 contentType;默认为 json serializer .postAs(Result.class); //for Bean generic type Result<User> body = HttpUtils.http("http://localhost:8080/book") .bodyOfBean(book) .postAs(new Result<User>(){}.getClass()); //通过临时类构建泛型(或别的方式) 

三、高级操作

获取完整的响应(用完要关闭)

 try(HttpResponse resp = HttpUtils.http("http://localhost:8080/hello").data("name","world").exec("POST")) { int code = resp.code(); String head = resp.header("Demo-Header"); String body = resp.bodyAsString(); Books body = resp.bodyAsBean(Books.class); } 

配置序列化器。默认为 json,比如改为 fury;或者自己定义。

 FuryBytesSerializer serializer = new FuryBytesSerializer(); Result body = HttpUtils.http("http://localhost:8080/book") .serializer(serializer) .bodyOfBean(book) .postAs(Result.class); 

四、总结

HttpUtils 的几个小优点:

  • 简单的 API。主要就是简单!也很小巧。
  • 支持自动序列化(使用了 solon serializer 接口规范;忆适配的序列化插件可直接用)
  • 支持泛型
原文链接:https://www.oschina.net/news/316219
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章