1
@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";        
}

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


客户端代码

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

1 回答 1

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 数据提供了强大的功能

于 2013-02-22T16:56:54.940 回答