没有架构的 Java REST 客户端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/359675/
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-10-29 12:04:51  来源:igfitidea点击:

Java REST client without schema

javaxmljaxbjax-rs

提问by Chase Seibert

Goal

目标

Java client for Yahoo's HotJobs Resumé Search REST API.

Yahoo 的 HotJobs Resumé Search REST API 的Java 客户端。

Background

背景

I'm used to writing web-service clients for SOAP APIs, where wsimportgenerates proxy stubs and you're off and running. But this is a REST API, which is new to me.

我习惯于为 SOAP API 编写 Web 服务客户端,其中wsimport生成代理存根,然后您就可以开始运行了。但这是一个 REST API,对我来说是新的。

Details

细节

Progress

进步

I looked at question Rest clients for Java?, but the automated solutions there assume you are providing both the server and the client, with JAXB invoked on POJOs to generate a schema and a REST API.

我查看了问题Java 的 Rest 客户端?,但那里的自动化解决方案假设您提供服务器和客户端,在 POJO 上调用 JAXB 以生成模式和 REST API。

Using Jersey(a JAX-RSimplementation), I have been able to make a manual HTTP request:

使用JerseyJAX-RS实现),我已经能够手动发出 HTTP 请求:

import com.sun.jersey.api.client.*;

...

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

WebResource webResource = client.resource("https://hj.yahooapis.com/v1/HJAuthTokens");
webResource.accept("application/xml");

// body is a hard-coded string, with replacements for the variable bits
String response = webResource.post(String.class, body);

// parse response into a org.w3c.dom.Document
// interface with Document via XPATH, or write my own POJO mappings

The response can look like:

响应可能如下所示:

<?xml version="1.0" encoding="utf-8"?>   
<Response>   
    <ResponseCode>0</ResponseCode>   
    <ResponseMessage>Login successful</ResponseMessage>
    <Token>NTlEMTdFNjk3Qjg4NUJBNDA3MkJFOTI3NzJEMTdDNDU7bG9jYWxob3N0LmVnbGJwLmNvcnAueWFob28uY29tO0pVNWpzRGRhN3VhSS4yQVRqRi4wWE5jTWl0RHVVYzQyX3luYWd1TjIxaGx6U0lhTXN3LS07NjY2MzM1OzIzNDY3NTsxMjA5MDE2OTE5OzZCM1RBMVNudHdLbl9VdFFKMFEydWctLQ==</Token>   
</Response>  

Or, it can look like:

或者,它看起来像:

<?xml version="1.0" encoding="utf-8"?>   
<yahoo:error xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" xml:lang="en-US">   
    <yahoo:description>description</yahoo:description>   
    <yahoo:detail>   
        <ErrorCode>errorCode</ErrorCode>   
    </yahoo:detail>   
</yahoo:error>  

Questions

问题

  • Is there a way to auto-generate POJOswhich can be marshalled/unmarshalled without a formal schema?
  • Should I attempt to generate those POJOs by hand, with JAXBannotations?
  • Is there some tool I should be leveraging so I don't have to do all this manually?
  • 有没有办法自动生成可以在没有正式模式的情况下编组/解组的POJO
  • 我是否应该尝试使用JAXB注释手动生成这些 POJO ?
  • 是否有一些我应该利用的工具,这样我就不必手动完成所有这些工作?

采纳答案by kdgregory

It's interesting that they provide an HTTP URL as the namespace URI for the schema, but don't actually save their schema there. That could be an oversight on their part, which an email or discussion-list posting could correct.

有趣的是,他们提供了一个 HTTP URL 作为架构的命名空间 URI,但实际上并没有将他们的架构保存在那里。这可能是他们的疏忽,电子邮件或讨论列表发布可以纠正。

One approach is to create your own schema, but this seems like a lot of work for little return. Given how simple the messages are, I wonder if you even need a POJO to wrap them? Why not just have a handler that extracts the data you need using XPath?

一种方法是创建您自己的模式,但这似乎是很多工作,但回报却很少。鉴于消息是多么简单,我想知道您是否甚至需要一个 POJO 来包装它们?为什么不只拥有一个使用 XPath 提取所需数据的处理程序呢?



Edit: blast from the past, but I saw the comment, reread the question, and realized that the first sentence was hard to understand. So, clarification:

编辑:从过去爆炸,但我看到评论,重新阅读问题,并意识到第一句话很难理解。所以,澄清:

One very good habit, if you're going to write a publicly accessible web service, is to make your schema document available at the same URL that you use for the schema's namespace URI -- or better, have that URL be a link to complete documentation (the W3C XSD namespace is itself a good example: http://www.w3.org/2001/XMLSchema).

如果您要编写可公开访问的 Web 服务,一个非常好的习惯是使您的架构文档在您用于架构的命名空间 URI 的相同 URL 处可用——或者更好的是,将该 URL 作为要完成的链接文档(W3C XSD 命名空间本身就是一个很好的例子:http: //www.w3.org/2001/XMLSchema)。

回答by StaxMan

I would suggest writing beans by hand, and only annotating with JAXB annotations if you have to. For most accessors/mutators (getters/setters) you do not have to; by default all public bean accessors and fields are considered, name is derived using bean convention, and default is to use elements instead of attributes (so attributes need to be annotated).

我建议手工编写 bean,如果需要,只使用 JAXB 注释。对于大多数访问器/修改器(getter/setter),您不必这样做;默认情况下,所有公共 bean 访问器和字段都被考虑,名称是使用 bean 约定派生的,默认是使用元素而不是属性(因此需要注释属性)。

Alternatively you can of course write schema by hand, generate beans using JAXB, if you like W3C Schema a lot. And just use resulting code, not schema, for data binding.

或者,如果您非常喜欢 W3C Schema,您当然可以手动编写模式,使用 JAXB 生成 bean。并且只使用结果代码,而不是模式,进行数据绑定。

As to POJO: that can be very simple. Something like:

至于 POJO:那可以很简单。就像是:

@XmlRootElement("Response")
class Response {
  public int responseCode;
  public String responseMessage;
  public String token; // or perhaps byte[] works for automated base64?
}

and similarly for other ones. Or, use getters/setters if you like them and don't mind bit more verbosity. These are just data containers, no need to get too fancy.

其他的也类似。或者,如果您喜欢它们并且不介意更冗长,请使用 getter/setter。这些只是数据容器,无需太花哨。

And if you must auto-detect type from content, consider using Stax parser to see what the root element, and then bind using JAXB Unmarshaller, handing XMLStreamReader that points to that root element. That way you can pass different object type to bind to.

如果您必须从内容中自动检测类型,请考虑使用 Stax 解析器查看根元素,然后使用 JAXB Unmarshaller 绑定,处理指向该根元素的 XMLStreamReader。这样你就可以传递不同的对象类型来绑定。

And finally: sending/receiving requests: plain old HttpURLConnection works ok for GET and POST requests (construct using, say, URL.openConnection()). Jakarta HttpClient has more features if need be. So oftentimes you don't really need a separate REST client -- they may come in handy, but generally build on simple http client pieces.

最后:发送/接收请求:普通的旧 HttpURLConnection 适用于 GET 和 POST 请求(使用 URL.openConnection() 构建)。如果需要,Jakarta HttpClient 具有更多功能。所以通常你并不真正需要一个单独的 REST 客户端——它们可能会派上用场,但通常建立在简单的 http 客户端部分上。

回答by StaxMan

I find HTTP4E very useful for making REST calls. It is an awesome Eclipse plugin, it has tabs, syntax coloring, auto suggest, code generation, REST HTTP call replay, etc.. It does a great job of HTTP debugging, HTTP tampering, hacking. I am having so much fun with it.

我发现 HTTP4E 对于进行 REST 调用非常有用。这是一个很棒的 Eclipse 插件,它有选项卡、语法着色、自动建议、代码生成、REST HTTP 调用重放等。它在 HTTP 调试、HTTP 篡改、黑客方面做得很好。我玩得很开心。

http://www.ywebb.com/

http://www.ywebb.com/

回答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