2016-04-19 95 views
0

我想与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。

你有什么想法吗?

回答

0

我找到了答案。 我们需要将protobuf视为一个字节[]。已经有一个这种类型的HttpMessageConverter。因此ResponseBody应该是

public byte[] openProto(@RequestHeader(value = "Host") String host, @RequestBody 
    byte[] strBody, HttpServletRequest httpRequest 
) throws InterruptedException { 
    return null; 
}