The doc for getReader says the data is interpreted based on a certain character set, so that could lead to the bytes getting garbled. Have you tried using getInputStream instead of getReader?
On Fri, Nov 10, 2023 at 8:47 AM Oliver Yasuna <[email protected]> wrote: > I am having trouble de-serializing a protobuf. I am confident that it is > serialized properly, as serialization works in all other cases. > > Here's a simplified proto file: > > ```proto3 > syntax = "proto3"; > > message Request { > oneof request { > LoginRequest login = 1; > SyncRequest sync = 2; > PushRequest push = 3; > } > } > > message LoginRequest { > string username = 1; > string password = 2; > } > > message SyncRequest { > } > > message PushRequest { > message Item { > int64 id = 1; > string value = 2; > string date = 3; > } > > repeated Item items = 1; > } > > ``` > > I read and de-serialize the protobuf in the `doPost` method of an > `HttpServlet`: > > ```java > @Override > protected void doPost(final HttpServletRequest httpRequest, final > HttpServletResponse httpResponse) throws ServletException, IOException { > final BufferedReader reader = httpRequest.getReader(); > final byte[] buffer = IOUtils.toByteArray(reader, > StandardCharsets.UTF_8); > > final Request request; > > try { > // TODO: Read from input stream directly. > request = Request.parseFrom(buffer); > } catch(final Exception e) { > throw new ServletException("Failed to deserialize request body.", e); > } > > // Never reaches this line. > // ... > } > ``` > > I get the following error: > > ``` > 11:44:23.199 [qtp1165303897-24] WARN o.e.j.ee10.servlet.ServletChannel - > handleException /api com.google.protobuf.InvalidProtocolBufferException: > While parsing a protocol message, the input ended unexpectedly in the > middle of a field. This could mean either that the input has been > truncated or that an embedded message misreported its own length. > ``` > > If I sent `Request.login` or `Request.sync`, it successfully > de-serializes. The error only occurs for `Request.push`. > > -- > You received this message because you are subscribed to the Google Groups > "Protocol Buffers" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To view this discussion on the web visit > https://groups.google.com/d/msgid/protobuf/e85e7551-1b04-4199-9bed-5e8ce0631747n%40googlegroups.com > <https://groups.google.com/d/msgid/protobuf/e85e7551-1b04-4199-9bed-5e8ce0631747n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- -Nadav -- You received this message because you are subscribed to the Google Groups "Protocol Buffers" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/CANZcNErE-dVAdtXN4WYjS3yxe1afwuapeFb6%3D%2BMYDtVtLCM7jQ%40mail.gmail.com.
