Java Jersey:接收表单参数作为字节数组

Dim*_* L. 6 java encoding bytearray jersey character-encoding

是否可以使用Jersey接收form参数作为字节数组?

我尝试了以下方法:

@Path("/someMethod")
@POST
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String someMethod(@FormParam("someParam") byte[] someParam)
{
    return "";
}
Run Code Online (Sandbox Code Playgroud)

但得到了这个错误:

SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
  SEVERE: Missing dependency for method public java.lang.String SomeClass.someMethod(byte[]) at parameter at index 0
  SEVERE: Missing dependency for method public java.lang.String SomeClass.someMethod(byte[]) at parameter at index 0
  SEVERE: Method, public java.lang.String SomeClass.someMethod(byte[]), annotated with POST of resource, class SomeClass, is not recognized as valid resource method.
Run Code Online (Sandbox Code Playgroud)

如果我将byte []更改为String,一切正常.

我需要以byte []而不是String的形式接收数据的原因是因为数据可能使用不同的字符集进行编码.它取决于提交数据的HTML文档,我需要在服务器端正确解码数据(编码字符集在单独的参数中提交).

所以,如果我能以byte []的形式接收数据,它将解决我的问题.任何其他解决方案也是受欢迎的.

谢谢!

Ale*_*aho 2

如果 Jersey 符合 JAX-RS 规范,则该参数可以是

  1. 原始类型
  2. 有一个接受单个 String 参数的构造函数
  3. 有一个名为 valueOf 的静态方法,它接受单个 String 参数(例如,请参见 Integer.valueOf(String))
  4. List、Set 或 SortedSet,其中 T 满足上述 2 或 3。生成的集合是只读的。

因为它实际上是在Jersey API中定义的。

如果您想最好地使用 @FormParam,您可以定义一个ByteArray类来处理由 String 转换引起的错误并将其用作参数类型。

  • 我仔细研究了球衣代码,注意到它包含“ByteArrayProvider”,它消耗并生成“MediaType.APPLICATION_OCTET_STREAM”并支持“byte[].class”。可能值得一试? (3认同)