Issue
I have a Jersey Web-Service that I need to parse some json data that was send along with a request.
@POST
@Path ("/authenticate")
@Produces (MediaType.APPLICATION_JSON)
public Response authenticate (@Context HttpServletRequest request)
{
try {
StringBuffer json = new StringBuffer ();
BufferedReader reader = request.getReader();
int line;
while ((line = reader.readLine()) != null)
{
json.append(line);
}
System.out.prinln (json);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return Response.ok().entity(json).build();
}//end authenticate method
This service generates the following Exception:
java.lang.IllegalStateException: getInputStream() has already been called for this request
I did some research that suggests a getReader
and getInputStream
cannot be called on the same request. Therefore, it seemed like a getInputStream
instance is already called. How is this possible if I haven't made a explicit call to it? To solve this problem, I used the getInputStream
method instead
try {
ServletInputStream reader = request.getInputStream();
int line;
while ((line = reader.read()) != -1)
{
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return Response.ok().entity().build();
With this approach, how can I use the int of bytes to get the json?
Solution
Seems like you're missing a @Consumes
annotation. You realise you can just have a method;
@POST
@Path ("/authenticate")
@Consumes (MediaType.APPLICATION_JSON)
@Produces (MediaType.APPLICATION_JSON)
public Response authenticate (String entity) {
//entity contains the posted content
}
Without having to read the stream yourself? If you have a bean representing your consumed JSON , then you can just add it as a method param and jersey will automatically parse it for you;
@POST
@Path ("/authenticate")
@Consumes (MediaType.APPLICATION_JSON)
@Produces (MediaType.APPLICATION_JSON)
public Response authenticate (AuthBean auth) {
//auth bean contains the parsed JSON
}
class AuthBean {
private String username;
private String password;
// getters/setters
}
Example post;
{
"username" : "[email protected]",
"password" : "super s3cret"
}
Answered By - Qwerky