1

我有一个 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() has already been called for this request

getReader我做了一些研究,表明getInputStream不能在同一个请求中调用。因此,似乎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?

4

2 回答 2

4

好像您缺少@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"
}
于 2013-07-22T14:31:23.600 回答
2

我们只能从 HttpServletRequest 读取一次,因此我们必须在读取请求之前在过滤器中使用HttpServletRequestWrapper并多次使用包装器进行后续调用。

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.dbs.bds.ingestion.util.MultiReadRequestWrapper;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SessionValidationFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    try {
        log.debug("inside filter");
        HttpServletRequest httpServletRequest = new MultiReadRequestWrapper((HttpServletRequest) servletRequest);
        filterChain.doFilter(httpServletRequest, servletResponse);
    } catch (Exception ex) {
        log.error("error inside filter:{}", ex.getMessage());
    }
 }
}

下面是我们在上面过滤器中使用的 Wrapper 的代码。

import org.apache.commons.io.input.BoundedInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class MultiReadRequestWrapper extends HttpServletRequestWrapper {
private static final Logger LOG = LoggerFactory.getLogger(MultiReadRequestWrapper.class);
// We include a max byte size to protect against malicious requests, 
//since this all has to be read into memory
public static final Integer MAX_BYTE_SIZE = 1_048_576; // 1 MB 
private StringBuilder body;
public MultiReadRequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    body = new StringBuilder("");
    try (
        InputStream bounded = new BoundedInputStream(request.getInputStream(), MAX_BYTE_SIZE);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bounded));){
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            body.append(line);
        }
    } catch(Exception e) {
        LOG.error(e.getMessage());
    }
}
@Override
public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.toString().getBytes());
    return new ServletInputStream() {
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }
        @Override
        public boolean isFinished() {
            return byteArrayInputStream.available() == 0;
        }
        @Override
        public boolean isReady() {
            return true;
        }
        @Override
        public void setReadListener(ReadListener readListener) {
            //do nothing
        }
    };
}
@Override
public BufferedReader getReader() throws IOException {
    return new BufferedReader(new InputStreamReader(this.getInputStream()));
 }
}

现在将上述过滤器公开为 bean

 @Bean(name = "sessionValidationFilter")
public Filter getSessionValidationFilter() {
    return new SessionValidationFilter();
}

@SuppressWarnings({"rawtypes", "unchecked"})
@Bean
public FilterRegistrationBean sessionValidationFilterRegistration() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(getSessionValidationFilter());
    registration.addUrlPatterns("/v1/create/record");
    registration.setName("sessionValidationFilter");
    return registration;
}
于 2019-07-31T13:02:21.227 回答