我正在研究Servlet并尝试记录请求。导致错误的代码的关键部分如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(request.getInputStream(), writer);
Message.Builder builder = something of type com.google.protobuf.GeneratedMessage.Builder;
builder.mergeFrom(writer.toString().getBytes());
}
上面的最后一行代码导致以下异常:
com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
但是,当代码切换到:
时protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Message.Builder builder = something of type com.google.protobuf.GeneratedMessage.Builder;
builder.mergeFrom(request.getInputStream());
}
没有错误,一切正常。问题是什么?我似乎需要类似于第一个代码片段的东西,因为我需要第二次使用输入流(一次将其写入文件,一次处理实际请求)。
答案 0 :(得分:1)
这个怎么样?
InputStream inputStream = request.getInputStream();
byte[] data = IOUtils.toByteArray(inputStream);
Message.Builder builder = something of type com.google.protobuf.GeneratedMessage.Builder;
builder.mergeFrom(data);
// then use inputStream for something else
答案 1 :(得分:0)
显然,我需要使用编码输入和输出流,以便可以正确读取数据。请参阅我的answer至我的其他问题。