如何访问 RESTful POST 方法中的参数

发布于 2024-12-16 19:44:14 字数 758 浏览 0 评论 0原文

我的 POST 方法如下所示:

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(String param1, String param2){
    System.out.println("param1 = " + param1);
    System.out.println("param2 = " + param2);
}

当我在 Netbeans 中创建 Jersey 客户端时,调用 post 方法的方法如下所示:

public void create(Object requestEntity){
    webResource.path("create").type(MediaType.APPLICATION_JSON).post(requestEntity);
}

运行此测试时:

@Test
public void hello(){
    String json = "{param1=\"hello\",param2=\"hello2\"}";
    this.client.create(json);
}

它在服务器中提供以下输出:

INFO: param1 = {param1="hello",param2="hello2"}
INFO: param2 = 

我需要更改什么以便参数给出了正确的值吗?

My POST method looks like this:

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(String param1, String param2){
    System.out.println("param1 = " + param1);
    System.out.println("param2 = " + param2);
}

When I create a Jersey Client in Netbeans the method who calls the post method looks like this:

public void create(Object requestEntity){
    webResource.path("create").type(MediaType.APPLICATION_JSON).post(requestEntity);
}

When running this test:

@Test
public void hello(){
    String json = "{param1=\"hello\",param2=\"hello2\"}";
    this.client.create(json);
}

It gives the following output in the server:

INFO: param1 = {param1="hello",param2="hello2"}
INFO: param2 = 

What do I need to change so that the parameters are giving the correct value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无风消散 2024-12-23 19:44:15

您的 @POST 方法应该接受 JSON 对象而不是字符串。 Jersey 使用 JAXB 支持编组和解组 JSON 对象(请参阅jersey 文档了解详细信息)。创建一个类,如下所示:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

那么您的 @POST 方法将如下所示:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

该方法期望接收 JSON 对象作为 HTTP POST 的正文。 JAX-RS 将 HTTP 消息的内容正文作为未注释的参数传递 - 在本例中为 input。实际的消息看起来像这样:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

由于显而易见的原因,以这种方式使用 JSON 是很常见的。但是,如果您使用 JavaScript 以外的其他方式生成或使用它,那么您必须小心正确地转义数据。在 JAX-RS 中,您可以使用 MessageBodyReader< /a> 和 MessageBodyWriter来实施这一点。我相信 Jersey 已经实现了所需类型(例如,Java 原语和 JAXB 包装类)以及 JSON。 JAX-RS 支持许多其他传递数据的方法。这些不需要创建新类,因为数据是使用简单的参数传递来传递的。


HTML

参数将使用 @FormParam

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

浏览器将使用 "application/x-www-form-urlencoded" 。 JAX-RS 运行时将负责解码主体并将其传递给方法。您应该在网络上看到以下内容:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello¶m2=world

内容是URL 编码的 在这种情况下。

如果您不知道 FormParam 的名称,您可以执行以下操作:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP 标头

您可以使用 @HeaderParam 注释:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

HTTP 消息如下所示。请注意,此帖子没有正文。

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

我不会使用此方法进行通用参数传递。如果您需要访问特定 HTTP 标头的值,它确实非常方便。


HTTP 查询参数

此方法主要用于 HTTP GET,但同样适用于 POST。它使用 @QueryParam 注释。

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

与之前的技术一样,通过查询字符串传递参数不需要消息正文。这是 HTTP 消息:

POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

您必须特别小心地正确对查询参数进行编码 在客户端。由于某些代理强制实施 URL 长度限制以及与编码相关的问题,使用查询参数可能会出现问题。


HTTP 路径参数

路径参数与查询参数类似,只不过它们嵌入在 HTTP 资源路径中。这种方法今天看来很受青睐。由于路径是真正定义 HTTP 资源的路径,因此会对 HTTP 缓存产生影响。该代码看起来与其他代码略有不同,因为 @Path 注释已修改,它使用 @PathParam< /a>:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

该消息类似于查询参数版本,但参数名称未包含在消息中的任何位置。

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

此方法与查询参数版本具有相同的编码问题。 路径段的编码方式不同,因此您也必须小心。


如您所见,每种方法都有优点和缺点。选择通常由您的客户决定。如果您提供基于 FORM 的 HTML 页面,请使用 @FormParam。如果您的客户端基于 JavaScript+HTML5,那么您可能需要使用基于 JAXB 的序列化和 JSON 对象。 MessageBodyReader/Writer 实现应该为您处理必要的转义,这样就可以减少可能出错的事情。如果您的客户端基于 Java,但没有良好的 XML 处理器(例如 Android),那么我可能会使用 FORM 编码,因为内容正文比 URL 更容易生成和正确编码。希望这个迷你 wiki 条目能够阐明 JAX-RS 支持的各种方法。

注意:为了充分披露,我还没有实际使用过 Jersey 的这个功能。我们正在对其进行修改,因为我们部署了许多 JAXB+JAX-RS 应用程序,并且正在进入移动客户端领域。 JSON 比 XML 更适合 HTML5 或基于 jQuery 的解决方案。

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello¶m2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello¶m2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文