泽西岛请求.getInputStream()

时间:2013-02-22 16:09:24

标签: java servlets jersey

@POST
@Path("/getphotos")
@Produces(MediaType.TEXT_HTML)
public String getPhotos() throws IOException{
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    return "ok";        
}

上面的代码适用于我的服务器。 但是在这段代码中,字符串“line”没有值。(总是) 代码有什么问题吗?


客户端代码

    String message = "message";
    URL url = new URL(targetURL);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
    wr.write(message);

1 个答案:

答案 0 :(得分:2)

可以 在Jersey中手动使用请求的数据,只要您拥有实际HttpServletRequest的有效句柄即可。请注意,请注意,您只能使用请求正文 一次

@Context
private HttpServletRequest request;

@POST
@Path("/")
public Response consumeRequest() {
    try {
        final BufferedReader rd = new BufferedReader(new InputStreamReader(
                request.getInputStream(), "UTF-8"));

        String line = null;
        final StringBuffer buffer = new StringBuffer(2048);

        while ((line = rd.readLine()) != null) {
            buffer.append(line);
        }
        final String data = buffer.toString();
        return Response.ok().entity(data).build();
    } catch (final Exception e) {
        return Response.status(Status.BAD_REQUEST)
                .entity("No data supplied").build();
    }
}

附注:Apache Commons IO等库提供了读取IO数据的强大功能