user757118
user757118

Reputation: 13

Jersey web service non-ascii characters

I am new to REST and jersey. I wrote a simple RESTful Web Service using Jersey 1.17 API. The Web service accepts data through POST method. When I pass data having non-ascii characters, it does not read them correctly.

@POST
@Path("hello")  
@Consumes(MediaType.APPLICATION_FORM_URLENCODED + ";charset=UTF-8")
public Response hello(@FormParam("message") String message) {       
    System.out.println(message);        
    return Response.status(200).entity("hello" + message).build();      
}

When I pass data having non-ascii characters in parameter 'message' it does not print it correctly.

curl --data "message=A função, Ãugent" http://localhost:8080/search/hello/

POST method prints "A fun??o, ?ugent"

Upvotes: 1

Views: 1416

Answers (1)

Balazs Zsoldos
Balazs Zsoldos

Reputation: 6046

I do not think Jersey is caring about the charset that is defined at @Consumes. I guess Jersey simply uses the request.getParameter method that uses the encoding of the request to resolve parameters.

You have many options to set the encoding:

  • In case the servlet container supports, set the default encoding of the connector
  • Set the default encoding of the jvm to UTF8
  • Create a Servlet Filter that catches this call and call request.setCharacterEncoding("UTF8"); In this case you must ensure that setCharacterEncoding is called before any other getter function (like getParameter) as the character encoding is set during the first get call on the request.
  • Do a transform on the parameter value by hand. You can get the ServletRequest and query the encoding. After that you can say:

new String(message.getBytes(currentEncoding), "UTF8");

In your case I would prefer the third one.

Upvotes: 1

Related Questions