You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
+++
|
|
|
|
|
title = "使用ResteasyClient请求接口"
|
|
|
|
|
date = 2020-04-08
|
|
|
|
|
draft = false
|
|
|
|
|
[taxonomies]
|
|
|
|
|
tags=["Java"]
|
|
|
|
|
+++
|
|
|
|
|
从OkHttp转到ResteasyClient
|
|
|
|
|
|
|
|
|
|
## Okhttp
|
|
|
|
|
|
|
|
|
|
以前一直用OkHttpclient访问api服务,参数复杂需要手工编码。
|
|
|
|
|
|
|
|
|
|
- query参数需要手工编码或者使用uribuilder构建完整url
|
|
|
|
|
- request body需要指定类型,不能使用类直接传参
|
|
|
|
|
|
|
|
|
|
## Retrofit
|
|
|
|
|
|
|
|
|
|
接手外包公司安卓项目时接触到Retrofit框架,一种使用动态代理机制将java接口转换成网络请求。主要好处就是解耦,分离api定义和使用。作为程序员,偷懒就是第一生产力,这么方便的使用api肯定要集成到项目中。跑到google搜了搜,看到ResteasyCient也支持proxy模式请求api,选择无情抛弃Retrofit,毕竟项目中引入了keycloak做认证和授权,自带了ResteasyClient
|
|
|
|
|
|
|
|
|
|
## ResteasyClient
|
|
|
|
|
|
|
|
|
|
Resteasy是一个实现了JAX-RS规范的轻量实现,该规范是针对基于http协议的RESTful Web Service而提供标准的JAVA API定义。
|
|
|
|
|
|
|
|
|
|
ResteasyClient是Resteasy提供的一个HttpClient,用来消费Resteasy api,项目使用maven作为包管理。
|
|
|
|
|
|
|
|
|
|
### 1. pom.xml
|
|
|
|
|
|
|
|
|
|
```xml
|
|
|
|
|
<properties>
|
|
|
|
|
<resteasy.version>3.9.1.Final</resteasy.version>
|
|
|
|
|
</properties>
|
|
|
|
|
<dependencies>
|
|
|
|
|
<dependency>
|
|
|
|
|
<groupId>org.jboss.resteasy</groupId>
|
|
|
|
|
<artifactId>resteasy-client</artifactId>
|
|
|
|
|
<version>${resteasy.version}</version>
|
|
|
|
|
</dependency>
|
|
|
|
|
...
|
|
|
|
|
</dependencies>
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
这个是keycloak内置的resteasy-client版本,也可以用最新的,不过最新版构建Client的方式略有不同
|
|
|
|
|
|
|
|
|
|
### 2. 代码
|
|
|
|
|
|
|
|
|
|
客户端代码主要设计三大类:
|
|
|
|
|
|
|
|
|
|
- **Client**
|
|
|
|
|
- **WebTarget**
|
|
|
|
|
- **Response**
|
|
|
|
|
|
|
|
|
|
WebTarget实例由Client生成。
|
|
|
|
|
|
|
|
|
|
每个WebTarget对应一个BaseUrl,项目中是可以有很多WebTarget。
|
|
|
|
|
|
|
|
|
|
生成Client实例的方式有两种:
|
|
|
|
|
|
|
|
|
|
- *org.jboss.resteasy.client.ClientRequest* 生成
|
|
|
|
|
- *ResteasyClientBuilder* 类生成
|
|
|
|
|
|
|
|
|
|
这里使用第二种方式构建client,用ResteasyClient就是为了偷懒。
|
|
|
|
|
|
|
|
|
|
### 3. api接口定义
|
|
|
|
|
|
|
|
|
|
定义好请求的端点:
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public interface AddressInterface {
|
|
|
|
|
@GET
|
|
|
|
|
@Path("/spider/geo")
|
|
|
|
|
List<LocationResult> getLocation(@QueryParam("addresses") String addresses);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
LocaltionResult类:
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
@Data
|
|
|
|
|
public class LocationResult {
|
|
|
|
|
private String location;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
这里使用了lombok简化代码
|
|
|
|
|
|
|
|
|
|
### 4. 请求接口
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
|
|
|
|
|
ResteasyClient client = new ResteasyClientBuilder().build();
|
|
|
|
|
ResteasyWebTarget target = client.target(UriBuilder.fromPath("https://127.0.0.1:8080"));
|
|
|
|
|
ServicesInterface proxy = target.proxy(AddressInterface.class);
|
|
|
|
|
List<LocationResult> results=proxy.getLocation("厦门市思明区塔埔东路169号2层201单元L室")
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
很简单
|