Java Jersey: Receive form parameter as byte array

2019-03-16 11:26发布

Is it possible to receive form parameter as byte array with Jersey?

I tried the following:

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

But got this error:

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.

If I change byte[] to String, everything works correctly.

The reason I need to receive data as byte[] and not as String is because data may be encoded using different charsets. It depends on the HTML document that submits data and I need to decode data correctly on server side (encoding charset is submitted in a separate parameter).

So, if I can receive data as byte[], it will solve my problem. Any other solutions are welcome as well.

Thank you!

2条回答
戒情不戒烟
2楼-- · 2019-03-16 11:38

If Jersey conforms to JAX-RS spec then the parameter may be

  1. A primitive type
  2. Have a constructor that accepts a single String argument
  3. Have a static method named valueOf that accepts a single String argument (see, for example, Integer.valueOf(String))
  4. List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.

as it is actually defined in the Jersey API.

If you want to use @FormParam the best you might be able to do define a ByteArray -class that handles the errors caused by the String conversion and use it as the parameter type.

查看更多
虎瘦雄心在
3楼-- · 2019-03-16 11:46

Thank you for your answers! I finally found a solution... Now that I see a solution, I understand that I didn't describe my problem well enough and it lead you to a different direction...

The problem was that I submit form data to the server from many different pages which use different encodings. When page uses utf-8 encoding, everything worked correctly but when page uses different encoding, special characters got lost.

The solution was to add accept-charset="utf-8" to the <FORM> html element, which caused browser to always encode form data to utf-8 encoding, which solved encoding problem on the server side.

Thank you!

查看更多
登录 后发表回答