Search code examples
restlet

strange failure GET in ServerResource with 1024*12+486 length response


I wrote a ServerResource below with restlet-android-2.1.4. If the I set SIZE to 1024 * 12 + 485, it works. But if I change SIZE to 1024 * 12 + 486 this handle will pending.

public class DataResource extends ServerResource {    
    public static final int SIZE = 1024 * 12 + 485;
    @Get
    public Representation getResource(Representation entity) {
        return new OutputRepresentation(MediaType.ALL) {
            @Override
            public void write(OutputStream outputStream) throws IOException {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < SIZE; i++) {
                    sb.append('E');
                }
                outputStream.write(sb.toString().getBytes());
                outputStream.close();
            }
        };
    }
}

Solution

  • Dive into the code, change the write function in WritableSocketChannel.java(in restlet source code) and it will work. I don't know whether it's a bug.

    from

    public int write(ByteBuffer src) throws IOException {
        return getWrappedChannel().write(src);
    }
    

    to

    public int write(ByteBuffer src) throws IOException {
        int count = 0;
        while (src.hasRemaining()) {
            count += getWrappedChannel().write(src);
        }
        return count;
    }
    

    According to java doc.

    Some types of channels, depending upon their state, may write only some of the bytes or possibly none at all. A socket channel in non-blocking mode, for example, cannot write any more bytes than are free in the socket's output buffer.