【发布时间】:2014-12-24 15:43:02
【问题描述】:
DropWizard 在 REST 的底层使用 Jersey。我试图弄清楚如何为我的 DropWizard 应用程序将公开的 RESTful 端点编写客户端。
为了这个例子,假设我的 DropWizard 应用程序有一个 CarResource,它公开了一些简单的 RESTful 端点用于 CRUDding 汽车:
@Path("/cars")
public class CarResource extends Resource {
// CRUDs car instances to some database (DAO).
public CardDao carDao = new CarDao();
@POST
public Car createCar(String make, String model, String rgbColor) {
Car car = new Car(make, model, rgbColor);
carDao.saveCar(car);
return car;
}
@GET
@Path("/make/{make}")
public List<Car> getCarsByMake(String make) {
List<Car> cars = carDao.getCarsByMake(make);
return cars;
}
}
所以我会想象结构化 API 客户端类似于CarServiceClient:
// Packaged up in a JAR library. Can be used by any Java executable to hit the Car Service
// endpoints.
public class CarServiceClient {
public HttpClient httpClient;
public Car createCar(String make, String model, String rgbColor) {
// Use 'httpClient' to make an HTTP POST to the /cars endpoint.
// Needs to deserialize JSON returned from server into a `Car` instance.
// But also needs to handle if the server threw a `WebApplicationException` or
// returned a NULL.
}
public List<Car> getCarsByMake(String make) {
// Use 'httpClient' to make an HTTP GET to the /cars/make/{make} endpoint.
// Needs to deserialize JSON returned from server into a list of `Car` instances.
// But also needs to handle if the server threw a `WebApplicationException` or
// returned a NULL.
}
}
但我能找到的仅有的两个关于 Drop Wizard 客户端的官方参考完全相互矛盾:
-
DropWizard recommended project structure - 它声称我应该将我的客户端代码放在
car.service.client包下的car-client项目中;但后来... - DropWizard Client manual - 这使它看起来像是一个“DropWizard 客户端”,用于将我的 DropWizard 应用程序与 其他 RESTful Web 服务集成(因此充当中间人)。
所以我问,为 DropWizard Web 服务编写 Java API 客户端的标准方法是什么? DropWizard 是否有可用于此类用例的客户端库?我应该通过一些 Jersey 客户端 API 来实现客户端吗?有人可以在我的CarServiceClient 中添加伪代码,以便我了解它是如何工作的吗?
【问题讨论】:
标签: java rest jersey dropwizard webservices-client