通过JSR 311及其实现,我们有了一个通过REST公开Java对象的强大标准。然而,在客户端,似乎缺少了一些类似于Apache Axis for SOAP的东西——隐藏web服务并将数据透明地封送回Java对象的东西。
如何创建Java RESTful客户端?使用HTTPConnection和手动解析结果?或者专门的客户端,例如Jersey或Apache CXR?
通过JSR 311及其实现,我们有了一个通过REST公开Java对象的强大标准。然而,在客户端,似乎缺少了一些类似于Apache Axis for SOAP的东西——隐藏web服务并将数据透明地封送回Java对象的东西。
如何创建Java RESTful客户端?使用HTTPConnection和手动解析结果?或者专门的客户端,例如Jersey或Apache CXR?
当前回答
我目前正在使用https://github.com/kevinsawicki/http-request,我喜欢他们的简单性和展示示例的方式,但当我阅读时,我主要是被卖了:
依赖关系是什么? 一个也没有。这个库的目标是成为带有一些内部静态类的单个类。测试项目确实需要Jetty,以便根据实际的HTTP服务器实现测试请求。
这解决了Java 1.6项目中的一些问题。至于把json解码成对象,gson是无敌的:)
其他回答
这是一个老问题(2008年),所以现在的选择比当时多得多:
Apache CXF有三个不同的REST客户端选项 泽西岛(上面提到过)。 Spring RestTemplate被Spring WebClient取代 公共HTTP客户端为旧的Java项目构建自己的。
更新(2020年仍然活跃的项目):
Apache HTTP Components (4.2) Fluent adapter - Basic replacement for JDK, used by several other candidates in this list. Better than old Commons HTTP Client 3 and easier to use for building your own REST client. You'll have to use something like Jackson for JSON parsing support and you can use HTTP components URIBuilder to construct resource URIs similar to Jersey/JAX-RS Rest client. HTTP components also supports NIO but I doubt you will get better performance than BIO given the short requestnature of REST. Apache HttpComponents 5 has HTTP/2 support. OkHttp - Basic replacement for JDK, similar to http components, used by several other candidates in this list. Supports newer HTTP protocols (SPDY and HTTP2). Works on Android. Unfortunately it does not offer a true reactor-loop based async option (see Ning and HTTP components above). However if you use the newer HTTP2 protocol this is less of a problem (assuming connection count is problem). Ning Async-http-client - provides NIO support. Previously known as Async-http-client by Sonatype. Feign wrapper for lower level http clients (okhttp, apache httpcomponents). Auto-creates clients based on interface stubs similar to some Jersey and CXF extensions. Strong spring integration. Retrofit - wrapper for lower level http clients (okhttp). Auto-creates clients based on interface stubs similar to some Jersey and CXF extensions. Volley wrapper for jdk http client, by google google-http wrapper for jdk http client, or apache httpcomponents, by google Unirest wrapper for jdk http client, by kong Resteasy JakartaEE wrapper for jdk http client, by jboss, part of jboss framework jcabi-http wrapper for apache httpcomponents, part of jcabi collection restlet wrapper for apache httpcomponents, part of restlet framework rest-assured wrapper with asserts for easy testing
关于选择HTTP/REST客户端的一个警告。确保检查你的框架栈为HTTP客户端使用了什么,它是如何执行线程的,如果它提供了一个客户端,最好使用相同的客户端。这是如果你使用像Vert。你可能想尝试使用它的后台客户端来参与框架提供的任何总线或反应器循环…否则,请为可能出现的有趣的线程问题做好准备。
OkHttp在与Retrofit结合使用时是轻量级和强大的。这适用于一般的Java使用,也适用于Android。
OkHttp: http://square.github.io/okhttp/
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
改造:http://square.github.io/retrofit/
public interface GitHubService {
@GET("/users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
由于没有人提到,这里有另一个:Feign,由Spring Cloud使用。
我大部分时间都使用RestAssured来解析rest服务响应和测试服务。除了Rest Assured之外,我还使用下面的库来与Resful服务进行通信。
a. Jersey Rest客户端
b. Spring RestTemplate
c. Apache HTTP Client
如果您只希望调用REST服务并解析响应,则可以尝试REST Assured
// Make a GET request to "/lotto"
String json = get("/lotto").asString()
// Parse the JSON response
List<String> winnderIds = with(json).get("lotto.winners.winnerId");
// Make a POST request to "/shopping"
String xml = post("/shopping").andReturn().body().asString()
// Parse the XML
Node category = with(xml).get("shopping.category[0]");