我想與protobuf和json做一個web服務工作。 問題在於我想要能夠讀取inputStream以構建我的原型(至少我沒有看到另一種方式)。web服務處理protobuf
我創建了protobuf的轉換器:
public class ProtobufMessageConverter extends AbstractHttpMessageConverter<MyProto>{
@Override
protected boolean supports(Class<?> aClass) {
return MyProto.class.equals(aClass);
}
@Override
protected MyProto readInternal(Class<? extends MyProto> aClass, HttpInputMessage httpInputMessage)
throws IOException, HttpMessageNotReadableException {
return MyProto.parseFrom(httpInputMessage.getBody());
}
@Override
protected void writeInternal(MyProto proto, HttpOutputMessage httpOutputMessage)
throws IOException, HttpMessageNotWritableException {
OutputStream wr = httpOutputMessage.getBody();
wr.write(proto.toByteArray());
wr.close();
}
}
在我springconfiguration使用:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.test")
public class SpringMvcConfiguration extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> httpMessageConverters) {
httpMessageConverters.add(new ProtobufMessageConverter(new MediaType("application","octet-stream")));
addDefaultHttpMessageConverters(httpMessageConverters);
}
}
我的控制器:
@RequestMapping(value = "/proto", method = {POST}, consumes = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
@ResponseBody
public MyProto openProto(@RequestHeader(value = "Host") String host, @RequestBody
MyProto strBody, HttpServletRequest httpRequest
) throws InterruptedException {
return null;
}
的問題是,如果我讓控制器一樣這個,我得到一個錯誤,因爲我的web服務不支持應用程序/八位字節流。
[主要] INFO org.eclipse.jetty.server.ServerConnector - 發起ServerConnector @ 73b05494 {HTTP/1.1} {0.0.0.0:8180} org.springframework.web.HttpMediaTypeNotSupportedException:內容類型「應用/ octet-流」不支持 在org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:155)...
如果我把字符串在@RequestBody,然後我往裏走我的方法,但它似乎沒有使用轉換器,並且該字符串不能用parseFrom函數強制轉換爲MyProto。
你有什麼想法嗎?