gpt4 book ai didi

json - Post/Put/Delete http Json with additional parameters in Jersey + 一般设计问题

转载 作者:行者123 更新时间:2023-12-04 20:02:52 25 4
gpt4 key购买 nike

出于某种原因,我还没有找到任何正常的方法来执行以下操作:

我想发布一个 json 对象,并向调用添加其他参数(在本例中为身份验证 token )。这是 myUrl/server 中的一个简单的 RESTful 服务器,它应该允许访问 url myUrl/server/person/personCode/resourceName 中“person”的不同资源。

GET 很简单,不需要对象,只需要参数。当我进行 POST 时出现问题 - 如何附加 JSON 并保留其他参数?

类(出于清晰度和专有原因,已经删除了很多...):

//Handles the person's resources
@Path("/person/{personCode}/{resourceName}")
public class PersonResourceProvider {

@GET
@Produces("application/json")
public String getPersonResource(@PathParam("personCode") String personCode, @PathParam("resourceName") String resourceName, @DefaultValue("") @QueryParam("auth_token") String auth_token) throws UnhandledResourceException, UnauthorizedAccessException {

//Authenticates the user in some way, throwing an exception when needed...
authenticate(personCode, auth_token, resourceName);

//Returns the resource somehow...
}

@POST
@Produces("application/json")
public String postPersonResource(@PathParam("personCode") String personCode, @PathParam("resourceName") String resourceName, @DefaultValue("") @QueryParam("resourceData") String resourceData, @DefaultValue("") @QueryParam("auth_token") String auth_token) throws UnhandledResourceException, UnauthorizedAccessException {

//Again, authenticating
authenticate(personCode, auth_token, resourceName);

//Post the given resource
}
}

现在,当您转到myUrl/person/personCode/resourceName,它给了我正确的资源。auth_token 用于对服务器的每次调用(目前,身份验证是通过与预定义的字符串进行比较来完成的),因此需要它。所有其他参数都通过路径提供,但身份验证 token 除外,它不应出现在路径中,因为它与所需资源的身份无关。

当我到达 POST 时,这是一个问题。我知道有一种方法可以告诉它使用 JSON 的方法,但在那种情况下,其他参数(auth_token 是其中之一)会发生什么?我应该使用多部分吗?

另外一个相关的问题,我是第一次设计这样的服务器,这样的设计是否正确?

谢谢!

最佳答案

我不确定我是否理解您要实现的目标。让我尝试解释一些事情 - 希望它与您的问题相关:@QueryParam 注入(inject)作为路径一部分的参数 - 即 URL 中“?”之后的部分。例如。如果您有这样的网址: http://yourserver.com/person/personCode/resourceName?resourceData=abc&token=1234

然后会有 2 个查询参数 - 一个名为 resourceData 的值为“abc”,另一个名为 token 的值为“1234”。

如果您在 POST 请求中传递一个实体,并且该实体是 application/json 类型,您可以使用 @Consumes("application/json") 注释简单地注释您的 post 方法并向您的方法添加另一个参数,根本不需要注释。该参数可以是一个字符串(在这种情况下,Jersey 将传递一个原始 JSON 字符串,您必须自己解析它)或者它可以是一个带有 @XmlRootElement 注释的 java bean - 在这种情况下(如果您还包括 jersey- json 模块) Jersey 将尝试使用 JAXB 将 json 字符串解码到该对象中。您还可以使用 Jackson 或 Jettison 库来执行此操作 - 有关更多信息,请参阅 Jersey 用户指南的这一部分:http://jersey.java.net/nonav/documentation/latest/json.html

关于json - Post/Put/Delete http Json with additional parameters in Jersey + 一般设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7430270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com