package test; import com.alibaba.fastjson.*; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class test { public static void main(String[] args) throws Exception { HttpResponse<String> response = Unirest.get("https://www.baidu.com/") .asString(); System.out.println(response.getBody()); String msg = JSON.parseObject("{\"status\":1,\"msg\":\"token 无效或者剩余次数0\"}").getString("msg"); System.out.println(msg); } }
UniRest是什么?
Unirest 是一套跨语言轻量级HTTP开发库,由Kong团队维护,此团队同时维护着另一个著名开源网关项目API Gateway Kong.
jar 包
http://zblog.kailigw.com/zb_users/upload/2020/05/lib.rar
MAVEN安装
<!-- 一般情形下maven引用的方式 --><dependency> <groupId>com.konghq</groupId> <artifactId>unirest-java</artifactId> <version>3.5.00</version></dependency><!-- 需要作为独立jar文件引用时(包含隐式依赖) --><dependency> <groupId>com.konghq</groupId> <artifactId>unirest-java</artifactId> <version>3.5.00</version> <classifier>standalone</classifier></dependenc
请求
使用JAVA语言,创建一个Unirest请求相当方便,一个常见的POST请求如下:
HttpResponse<JsonNode> response =Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .queryString("apiKey", "123") .field("parameter", "value") .field("foo", "bar") .asJson();
路由参数
如果需要在URL中加入动态路由参数,可以先在URL中通过一个占位符标记参数位置,之后通过routeParam方法,动态指定参数值,如下所示:
Unirest.get("http://httpbin.org/{fruit}") .routeParam("fruit", "apple") .asString();
占位符的格式为{自定义名称},在示例中,{占位符}会被替换为 apple,并且所有占位符会自动使用
URL-Encoded转义。
查询参数
请求路径附带的参数可以通过如下方式逐个添加
Unirest.get("http://httpbin.org") .queryString("fruit", "apple") .queryString("droid", "R2D2") .asString();// 请求路径 "http://httpbin.org?fruit=apple&droid=R2D2"
请求头
请求头通过header方法,添加:
Unirest.get("http://httpbin.org") .header("Accept", "application/json") .header("x-custom-header", "hello") .asString();
Basic Authentication 认证
Unirest提供了一个方便的方法实现 Basic Authentication 认证,Unirest 会自动处理Base64编码部分,此认证建议使用HTTPS。
作者:wzhwizard
链接:https://www.jianshu.com/p/057fae753c26
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Unirest.get("http://httpbin.org") .basicAuth("user", "password1!") .asString();// 请求头 "Authorization: Basic dXNlcjpwYXNzd29yZDEh"
请求体
请求体通过body方法指定,除非特别指定,否则请求头中 Content-Type 统一设置为:text/plain; charset=UTF-8
Unirest.post("http://httpbin.org") .body("This is the entire body") .asEmpty();
body方法传入对象,支持用Jackson序列化对象方式生成请求体。
Unirest.post("http://httpbin.org") .header("Content-Type", "application/json") .body(new SomeUserObject("Bob")) .asEmpty();// This will use Jackson to serialize the object into JSON.
JSON Patch支持
Unirest 原生支持JSON Patch 技术(参见 RFC-6902 http://jsonpatch.com/) 。json-patch请求默认的Content-Type是application/json-patch+json。
Unirest.jsonPatch("http://httpbin.org") .add("/fruits/-", "Apple") .remove("/bugs") .replace("/lastname", "Flintstone") .test("/firstname", "Fred") .move("/old/location", "/new/location") .copy("/original/location", "/new/location") .asJson();
以上代码会生成以下请求内容并发送
[ {"op":"add","path":"/fruits/-","value":"Apple"}, {"op":"remove","path":"/bugs"}, {"op":"replace","path":"/lastname","value":"Flintstone"}, {"op":"test","path":"/firstname","value":"Fred"}, {"op":"move","path":"/new/location","from":"/old/location"}, {"op":"copy","path":"/new/location","from":"/original/location"} ]
基本表单
通过body传输的表单name和value参数可以通过field指定,此类请求的Content-Type默认为application/x-www-form-urlencoded
Unirest.post("http://httpbin.org") .field("fruit", "apple") .field("droid", "R2D2") .asEmpty();
文件上传
可以通过POST表单提交二进制数据,例如:文件。这种类型的请求中,Content-Type默认为multipart/form-data。
Unirest.post("http://httpbin.org") .field("upload", new File("/MyFile.zip")) .asEmpty();
对于大文件上传,可以通过InputStream方式上传,同时可以附加文件名。示例中使用FileInputStream举例,实际上也同时支持各类InputStream。
InputStream file = new FileInputStream(new File("/MyFile.zip"));Unirest.post("http://httpbin.org") .field("upload", file, "MyFile.zip") .asEmpty();
在上传大文件时,如果需要向用户展示进度条,可以通过提供一个ProgresMonitor来实现:
Unirest.post("http://httpbin.org") .field("upload", new File("/MyFile.zip")) .uploadMonitor((field, fileName, bytesWritten, totalBytes) -> { updateProgressBarWithBytesLeft(totalBytes - bytesWritten); }) .asEmpty();
异步请求
所有请求都支持异步版本,示例如下
CompletableFuture<HttpResponse<JsonNode>> future = Unirest.post("http://httpbin.org/post") .header("accept", "application/json") .field("param1", "value1") .field("param2", "value2") .asJsonAsync(response -> { int code = response.getStatus(); JsonNode body = response.getBody(); });
请求分页
有些服务提供分页数据,Unirest可以通过一种标准方式,自动拉去全部数据。
使用这个功能需要提供两个方法参数。 第一个方法将返回内容转换为需要的HttpResponse对象, 另一个方法从返回内容中获取下一页的URL链接地址。此功能返回PagedList<HttpResponse<T>>对象。 PagedList对象封装了处理返回结果的一些常用方法。
以下示例中,Unirest自动分页拉取了Do。
PagedList<Doggos> result = Unirest.get("https://somewhere/dogs") .asPaged( r -> r.asObject(Doggos.class), r -> r.getHeaders().getFirst("nextPage") );
代理
Unirest支持通过proxy方法配置代理。需要注意的是,unirest不支持为单个请求,配置带有权限验证的代理,除非权限验证内容构建在URL中。
// 配置带有权限验证的代理Unirest.config().proxy("proxy.com", 7777, "username", "password1!");// 或使用无权限验证的代理Unirest.config().proxy("proxy.com", 7777);// 通过请求指定代理,这样会覆盖默认代理// 这种情况下,只有不需要验证的代理可以生效Unirest.get(MockServer.GET) .proxy("proxy.com", 7777) .asString();
返回值
Unirest 在调用as[type]方法时,实际发送请求。这类方法同时限定了返回值类型。例如:Empty, String, File, Object, byte and Json.
返回值对象HttpResponse<T> 封装了例如:status,headers等。返回值body内容,通过getBody() 获取。
返回空值
如果不需要处理返回body内容,asEmpty是一个十分好用的方法,返回内容仍然包含status 和headers。
HttpResponse response = Unirest.delete("http://httpbin.org").asEmpty()
返回字符串
另一个方便的方法是通过asString方法获取返回字符串。
String body = Unirest.get("http://httpbin.org") .asString() .getBody();
返回对象处理
通常使用RESTful 服务时,会对返回值进行json对象转换。在这种情况下,需要为Unirest指定ObjectMapper (参见ObjectMapper )。
Unirest 默认通过Google GSON来处理JSON数据。如果不希望使用默认处理方式,在使用asObject(Class)方法前,需要向Unirest提供ObjectMapper 接口的自定义实现。在初次指定之后,ObjectMapper 对象会被全局共享。
Unirest 同时提供一些ObjectMapper 插件, 例如:Jackson 、Gson. 可以通过maven center了解详情。
作者:wzhwizard
链接:https://www.jianshu.com/p/057fae753c26
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
// 返回对象Book book = Unirest.get("http://httpbin.org/books/1") .asObject(Book.class) .getBody();// 通过GenericType支持构建泛型对象List<Book> books = Unirest.get("http://httpbin.org/books/") .asObject(new GenericType<List<Book>>(){}) .getBody();Author author = Unirest.get("http://httpbin.org/books/{id}/author") .routeParam("id", bookObject.getId()) .asObject(Author.class) .getBody();
对象返回值异常处理
在JSON转化为对象过程中出现异常时,body返回值为null,需要通过getParsingError获取异常信息和返回的body值。
UnirestParsingException ex = response.getParsingError().get();ex.getOriginalBody(); // 返回body原始值ex.getMessage(); // 处理过程出现的异常信息ex.getCause(); // 原始parsing exception
错误信息对象映射
有些场景下,REST API’s 会返回错误信息对象,通过以下方式可以进行转换HttpResponse<Book> book = Unirest.get("http://httpbin.org/books/{id}") .asObject(Book.class); // 在没有错误的情况下,此方法返回null Error er = book.mapError(Error.class); // ifFailure 方法中也可以做类似自动转换 Unirest.get("http://httpbin.org/books/{id}") .asObject(Book.class) .ifFailure(Error.class, r -> { Error e = r.getBody(); });
配置不同客户端
通常,Unirest维护一个主单例对象。但有些情况下,例如:需要为不同系统设定不同配置,或需要为测试目的避开静态上下文时,可以使用如下方式:
//第一个Unirest对象 UnirestInstance unirest = Unirest.primaryInstance(); unirest.config().connectTimeout(5000); String result = unirest.get("http://foo").asString().getBody(); //第二个Unirest对象 UnirestInstance unirest = Unirest.spawnInstance();
关闭连接
Unirest 启动了一个后台事件总线 ,需要调用以下方法才能关闭
Unirest.shutdown();