gpt4 book ai didi

java.lang.IllegalStateException : getInputStream() has already been called for this request

转载 作者:行者123 更新时间:2023-12-01 18:46:02 25 4
gpt4 key购买 nike

我有一个 Jersey Web 服务,我需要解析一些随请求一起发送的 json 数据。

@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

此服务生成以下异常:

java.lang.IllegalStateException:已为此请求调用 getInputStream()

我做了一些研究,表明不能在同一请求上调用 getReadergetInputStream。因此,似乎已经调用了 getInputStream 实例。如果我没有明确调用它,这怎么可能?为了解决这个问题,我改用了getInputStream方法

    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();

通过这种方法,我如何使用 int 字节来获取 json?

最佳答案

似乎您缺少 @Consumes 注释。你意识到你可以有一个方法;

@POST
@Path ("/authenticate")
@Consumes (MediaType.APPLICATION_JSON)
@Produces (MediaType.APPLICATION_JSON)
public Response authenticate (String entity) {

//entity contains the posted content

}

无需自己阅读流?如果您有一个代表您使用的 JSON 的 bean,那么您只需将其添加为方法参数,jersey 就会自动为您解析它;

@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

}

示例帖子;

{
"username" : "joe@example.com",
"password" : "super s3cret"
}

关于java.lang.IllegalStateException : getInputStream() has already been called for this request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17790048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com