通过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?
当前回答
您可以使用标准的Java SE api:
private void updateCustomer(Customer customer) {
try {
URL url = new URL("http://www.example.com/customers");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/xml");
OutputStream os = connection.getOutputStream();
jaxbContext.createMarshaller().marshal(customer, os);
os.flush();
connection.getResponseCode();
connection.disconnect();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
或者您可以使用JAX-RS实现(如Jersey)提供的REST客户机api。这些api更容易使用,但在类路径上需要额外的jar。
WebResource resource = client.resource("http://www.example.com/customers");
ClientResponse response = resource.type("application/xml");).put(ClientResponse.class, "<customer>...</customer.");
System.out.println(response);
有关更多信息,请参阅:
http://bdoughan.blogspot.com/2010/08/creating-restful-web-service-part-55.html
其他回答
如果您只希望调用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]");
我想指出另外两个选项:
Restfulie基于VRaptor web框架,拥有非常好的超媒体支持的服务器端和客户端实现。 RESTEasy有一个基于JAX-RS代理的客户端实现。
我最近尝试了从square的Retrofit Library,它很棒,你可以很容易地调用你的rest API。 基于注释的配置使我们摆脱了大量的锅炉板编码。
这是一个老问题(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。你可能想尝试使用它的后台客户端来参与框架提供的任何总线或反应器循环…否则,请为可能出现的有趣的线程问题做好准备。
尽管创建一个HTTP客户端并进行重新测试很简单。但是如果你想利用一些自动生成的客户端,你可以使用WADL来描述和生成代码。
您可以使用RestDescribe来生成和编译WSDL,也可以使用它生成php、ruby、python、java和c#中的客户端。它可以生成干净的代码,并且在代码生成之后,你需要对它进行一些调整,你可以在这里找到良好的文档和工具背后的潜在思想。
wintermute中提到了一些有趣而有用的WADL工具。