ashishl ashishl - 3 months ago 14
JSON Question

Getting syntax error for Spring security with Jersey Rest API

I am doing authentication for REST Services.

So If user is unauthenticated then I want to send the user as "unauthenticated user" as repsonse in JSON format.

below is my code . I have set the content type as APPLICATION_JSON then I am getting the response as syntax error on postman tool. I can see the exact error in plainText or in Xml but not able to see the response in JSON.

Could anybody help me to get out from this issu please.

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("Connection", "keep-alive");
response.setContentType(MediaType.APPLICATION_JSON);
String msg = authException.getMessage();
response.getOutputStream().println("{ \"error\": \"" + msg+ "\" }");
}
}

Answer

I think you are doing it in wrong way the method syntax in ServeletResponse class is:

void setContentType(java.lang.String type)

so it should be like this

response.setContentType("application/json;charset=UTF-8");

Hope this helps.