如何为 Java 创建 REST 客户端?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/221442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:37:14  来源:igfitidea点击:

How do you create a REST client for Java?

javarestclient

提问by Yaba

With JSR 311 and its implementations we have a powerful standard for exposing Java objects via REST. However on the client side there seems to be something missing that is comparable to Apache Axis for SOAP - something that hides the web service and marshals the data transparently back to Java objects.

有了 JSR 311 及其实现,我们有了一个强大的标准,可以通过 REST 公开 Java 对象。然而,在客户端似乎缺少一些与 Apache Axis for SOAP 相当的东西——隐藏 Web 服务并将数据透明地编组回 Java 对象的东西。

How do you create Java RESTful clients? Using HTTPConnection and manual parsing of the result? Or specialized clients for e.g. Jersey or Apache CXR?

您如何创建 Java RESTful 客户端?使用 HTTPConnection 并手动解析结果?还是专门的客户,例如 Jersey 或 Apache CXR?

采纳答案by Adam Gent

This is an old question (2008) so there are many more options now than there were then:

这是一个老问题(2008 年),所以现在有比当时更多的选择:

UPDATES (projects still active in 2020):

更新(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 Hymanson for JSON parsingsupport and you can use HTTP components URIBuilder to construct resource URIssimilar 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 5has 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-clientby Sonatype.
  • Feignwrapper 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.
  • Volleywrapper for jdk http client, by google
  • google-httpwrapper for jdk http client, or apache httpcomponents, by google
  • Unirestwrapper for jdk http client, by kong
  • ResteasyJakartaEE wrapper for jdk http client, by jboss, part of jboss framework
  • jcabi-httpwrapper for apache httpcomponents, part of jcabi collection
  • restletwrapper for apache httpcomponents, part of restlet framework
  • rest-assuredwrapper with asserts for easy testing
  • Apache HTTP 组件 (4.2) Fluent 适配器- JDK 的基本替代品,被此列表中的其他几个候选者使用。比旧的 Commons HTTP Client 3 更好,更容易用于构建自己的 REST 客户端。您必须使用Hymanson 之类的东西支持JSON 解析,并且您可以使用HTTP 组件 URIBuilder 来构建类似于 Jersey/JAX-RS Rest 客户端的资源 URI。HTTP 组件也支持 NIO,但鉴于 REST 的短请求特性,我怀疑您会获得比 BIO 更好的性能。Apache HttpComponents 5支持 HTTP/2。
  • OkHttp- JDK 的基本替代品,类似于 http 组件,被此列表中的其他几个候选者使用。支持较新的 HTTP 协议(​​SPDY 和 HTTP2)。适用于Android。不幸的是,它没有提供真正的基于反应器循环的异步选项(参见上面的 Ning 和 HTTP 组件)。但是,如果您使用较新的 HTTP2 协议,这不是问题(假设连接数是问题)。
  • Ning Async-http-client- 提供 NIO 支持。以前被Sonatype称为Async-http-client
  • 低级 http 客户端(okhttp、apache httpcomponents)的伪装包装器。基于类似于某些 Jersey 和 CXF 扩展的接口存根自动创建客户端。强大的弹簧集成。
  • 改造- 较低级别的 http 客户端(okhttp)的包装器。基于类似于某些 Jersey 和 CXF 扩展的接口存根自动创建客户端。
  • jdk http 客户端的Volley包装器,由谷歌提供
  • 用于 jdk http 客户端或 apache httpcomponents 的google-http包装器,由 google 提供
  • 用于 jdk http 客户端的Unirest包装器,作者:kong
  • 用于 jdk http 客户端的ResteasyJakartaEE 包装器,由 jboss 提供,是 jboss 框架的一部分
  • apache httpcomponents 的jcabi-http包装器,jcabi 集合的一部分
  • apache httpcomponents 的restlet包装器,restlet 框架的一部分
  • 带有断言的放心包装器,便于测试

A caveat on picking HTTP/REST clients. Make sure to check what your framework stack is using for an HTTP client, how it does threading, and ideally use the same client if it offers one. That is if your using something like Vert.x or Play you may want to try to use its backing client to participate in whatever bus or reactor loop the framework provides... otherwise be prepared for possibly interesting threading issues.

关于选择 HTTP/REST 客户端的警告。确保检查您的框架堆栈用于 HTTP 客户端的内容,它如何进行线程处理,并且最好使用相同的客户端(如果提供)。也就是说,如果您使用 Vert.x 或 Play 之类的东西,您可能想尝试使用其支持客户端来参与框架提供的任何总线或反应器循环……否则为可能有趣的线程问题做好准备。

回答by JeeBee

I use Apache HTTPClient to handle all the HTTP side of things.

我使用 Apache HTTPClient 来处理所有 HTTP 方面的事情。

I write XML SAX parsers for the XML content that parses the XML into your object model. I believe that Axis2 also exposes XML -> Model methods (Axis 1 hid this part, annoyingly). XML generators are trivially simple.

我为 XML 内容编写了 XML SAX 解析器,将 XML 解析为您的对象模型。我相信 Axis2 也暴露了 XML -> 模型方法(Axis 1 隐藏了这部分,很烦人)。XML 生成器非常简单。

It doesn't take long to code, and is quite efficient, in my opinion.

在我看来,编写代码不需要很长时间,而且效率很高。

回答by James Strachan

As I mentioned in this threadI tend to use Jerseywhich implements JAX-RS and comes with a nice REST client. The nice thing is if you implement your RESTful resources using JAX-RS then the Jersey client can reuse the entity providers such as for JAXB/XML/JSON/Atom and so forth - so you can reuse the same objects on the server side as you use on the client side unit test.

正如我在这个帖子中提到的,我倾向于使用Jersey,它实现了 JAX-RS 并带有一个很好的 REST 客户端。好消息是,如果您使用 JAX-RS 实现 RESTful 资源,那么 Jersey 客户端可以重用实体提供程序,例如 JAXB/XML/JSON/Atom 等 - 因此您可以在服务器端重用与您相同的对象在客户端单元测试中使用。

For example here is a unit test casefrom the Apache Camel projectwhich looks up XML payloads from a RESTful resource (using the JAXB object Endpoints). The resource(uri) method is defined in this base classwhich just uses the Jersey client API.

例如,这里有一个来自Apache Camel 项目的单元测试用例,它从 RESTful 资源(使用 JAXB 对象端点)查找 XML 有效负载。resource(uri) 方法在这个基类中定义,它只使用 Jersey 客户端 API。

e.g.

例如

    clientConfig = new DefaultClientConfig();
    client = Client.create(clientConfig);

    resource = client.resource("http://localhost:8080");
    // lets get the XML as a String
    String text = resource("foo").accept("application/xml").get(String.class);        

BTW I hope that future version of JAX-RS add a nice client side API along the lines of the one in Jersey

顺便说一句,我希望 JAX-RS 的未来版本能够像 Jersey 中的那样添加一个很好的客户端 API

回答by Jerome Louvel

You can also check Restletwhich has full client-side capabilities, more REST oriented that lower-level libraries such as HttpURLConnection or Apache HTTP Client (which we can leverage as connectors).

您还可以检查具有完整客户端功能的Restlet,更多面向 REST 的低级别库,例如 HttpURLConnection 或 Apache HTTP Client(我们可以将其用作连接器)。

Best regards, Jerome Louvel

最好的问候,杰罗姆·卢维尔

回答by Jerome Louvel

You could try Rapa. Let us know your feedback about the same. And feel free to log issues or expected features.

你可以试试拉帕。让我们知道您对此的反馈。并随时记录问题或预期功能。

回答by bdoughan

You can use the standard Java SE APIs:

您可以使用标准的 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); 
    } 
} 

Or you can use the REST client APIs provided by JAX-RS implementations such as Jersey. These APIs are easier to use, but require additional jars on your class path.

或者,您可以使用 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); 

For more information see:

有关更多信息,请参阅:

回答by Johan

If you only wish to invoke a REST service and parse the response you can try out Rest Assured

如果您只想调用 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]");

回答by Ophir Radnitz

I'd like to point out 2 more options:

我想指出另外两个选项:

回答by yegor256

Try JdkRequestfrom jcabi-http(I'm a developer). This is how it works:

JdkRequestjcabi-http尝试(我是开发人员)。这是它的工作原理:

String body = new JdkRequest("http://www.google.com")
  .header("User-Agent", "it's me")
  .fetch()
  .body()

Check this blog post for more details: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

查看此博客文章了解更多详情:http: //www.yegor256.com/2014/04/11/jcabi-http-intro.html

回答by GG.

Though its simple to create a HTTP client and make a reuest. But if you want to make use of some auto generated clients, You can make use of WADL to describe and generate code.

尽管创建 HTTP 客户端并进行请求很简单。但是如果你想利用一些自动生成的客户端,你可以利用 WADL 来描述和生成代码。

You can use RestDescribeto generate and compile WSDL, you can generate clients in php, ruby, python, java and C# using this. It generates clean code and there is a good change that you have to tweak it a bit after code generation, you can find good documentation and underlying thoughts behind the tool here.

您可以使用RestDescribe生成和编译 WSDL,您可以使用它生成 php、ruby、python、java 和 C# 中的客户端。它生成干净的代码,并且有一个很好的更改,您必须在代码生成后对其进行一些调整,您可以在此处找到该工具背后的良好文档和基本思想。

There are few interesting and useful WADL toolsmentioned on wintermute.

在 Wintermute 上提到的有趣和有用的WADL 工具很少。