向 REST 服务发布复杂参数,请求 URL 和 Body 是什么样的 [英] POST complex parameters to REST service what would request URL and Body look like
问题描述
所以我站起来休息.它将请求一个非常复杂的资源的帖子.实际后端需要多个(19!)参数.其中之一是字节数组.听起来这需要由客户端序列化并发送到我的服务.
So I am standing up a rest service. It is going to request a post to a resource that is pretty complex. The actual backend requires multiple (19!) parameters. One of which is a byte array. It sounds like this is going to need to be serialized by the client and sent to my service.
我正在尝试了解如何正确处理此问题的方法.我在想这样的事情
I am trying to understand how I can right a method that will handle this. I am thinking something like this
@POST
@Path("apath")
@Consumes(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)
public Response randomAPI(@Parameter apiID, WhatParamWouldIPutHere confused){
}
我将使用哪些参数类型来捕获入站(序列化)发布数据.客户端 URI 会是什么样子?
What parameter types would I do to capture that inbound (Serialized) Post data. And what would the client URI look like?
推荐答案
为了得到请求的所有参数,你可以使用 @Context UriInfo
作为你的 randomAPI
的参数代码>方法.
In order to get all the parameters of the request you can use @Context UriInfo
as parameter of your randomAPI
method.
然后使用UriInfo#getQueryParameters()
获取完整的MultivaluedMap
参数.
如果您希望将 MultivaluedMap
转换为简单的 HashMap
,我也为此添加了代码.
if you wish to convert the MultivaluedMap
to a simple HashMap
I added the code for that too.
所以你的方法基本上看起来像这样:
so your method will basically look like something like this:
@POST
@Path("apath")
@Consumes(MediaType.APPLICATION_JSON, MediaType.TEXT_HTML)
public Response randomAPI(@Context UriInfo uriInfo){
Map params= (HashMap) convertMultiToHashMap(uriInfo.getQueryParameters());
return service.doWork(params);
}
public Map<String, String> convertMultiToHashMap(MultivaluedMap<String, String> m) {
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<String, List<String>> entry : m.entrySet()) {
StringBuilder sb = new StringBuilder();
for (String s : entry.getValue()) {
sb.append(s);
}
map.put(entry.getKey(), sb.toString());
}
return map;
}
附加信息:
@Context
注释允许您注入javax.ws.rs.core.HttpHeaders
、javax.ws.rs.core.UriInfo
、javax.ws.rs.core.Request
, javax.servlet.HttpServletRequest
,javax.servlet.HttpServletResponse
、javax.servlet.ServletConfig
、javax.servlet.ServletContext
和 javax.ws.rs.core.SecurityContext
对象.
The
@Context
annotation allows you to inject instances ofjavax.ws.rs.core.HttpHeaders
,javax.ws.rs.core.UriInfo
,javax.ws.rs.core.Request
,javax.servlet.HttpServletRequest
,javax.servlet.HttpServletResponse
,javax.servlet.ServletConfig
,javax.servlet.ServletContext
, andjavax.ws.rs.core.SecurityContext
objects.
这篇关于向 REST 服务发布复杂参数,请求 URL 和 Body 是什么样的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!