RESTful资源返回HTTP 204,但客户端显示200

时间:2016-08-17 17:41:13

标签: rest http jersey jax-rs java-ee-6

我正在编写RESTful Web服务。我使用的技术:

  • Glassfish 3(基于Java EE 6)
  • Jersey(应用程序服务器的一部分)
  • JDK v7
  • Eclipse EE Kepler IDE

资源方法:

@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Path("/uploadDownloadFile")
public Response uploadDownloadFile(InputStream input){

    if(Files.exists(Paths.get(resource))){//stream data out
        ...
    }
    else{
        String result = "The file \""+downFileName+"\" has not been found!";

        ByteArrayOutputStream b = new ByteArrayOutputStream();

        try {
            b.write(result.getBytes("UTF-8"));
        } catch(IOException e){
            e.printStackTrace();
        }

        response = Response.status(204).entity(b.toByteArray()).build();
    }

    return response;
}

也就是说,当文件不存在时,响应状态为204

客户端部分:

int code = connect.getResponseCode();

System.out.println("Upload Status: "+code+" : "+connect.getResponseMessage());

InputStream input = connect.getInputStream();

if(code > 200){
    downFileName = "Err.txt";
}

saveFile(input, downFileName);

现在,我所做的是执行客户端代码,并确保服务方法接收的文件不可用。这意味着,服务方法的响应应该包含代码204

虽然,当我实际执行客户端时,我会收到以下状态报告(在上面的源代码中):

Upload Status: 200 : OK

其他信息:

当我在客户端运行调试器时,我进入了这个JDK(HttpURLConnection.class)方法:

/**
     * Gets the status code from an HTTP response message.
     * For example, in the case of the following status lines:
     * <PRE>
     * HTTP/1.0 200 OK
     * HTTP/1.0 401 Unauthorized
     * </PRE>
     * It will return 200 and 401 respectively.
     * Returns -1 if no code can be discerned
     * from the response (i.e., the response is not valid HTTP).
     * @throws IOException if an error occurred connecting to the server.
     * @return the HTTP Status-Code, or -1
     */
 ` public int getResponseCode() throws IOException {}`

最初,responseCode-1,这意味着,根据上述文档:the response is not valid HTTP。最后,它会变成HTTP 200代码。

百科:

 204 No Content
    The server successfully processed the request and is not returning any content

为什么客户端的状态代码与服务的响应不同?

0 个答案:

没有答案