通过REST发送协议缓冲区

时间:2010-07-06 14:46:26

标签: rest protocol-buffers jax-rs

我正在尝试使用REST为客户端/服务器实现协议缓冲区。 如果我需要以字节格式发送协议缓冲区请求,我仍然有点困惑吗?

我的意思是,在我的客户端代码中,我是否需要将对象序列化为字节数组? 例如

protoRequest.build.toByteArray()

在服务器中,我是否需要c

   @POST
   @Consumes("application/octet-stream")
   public byte[] processProtoRequest(byte[] protoRequest) {
   ProtoRequest.Builder request = ProtoRequest.newBuilder();
   request.mergeFrom(protoRequest)
}

这是正确的做法吗?

由于

大卫

3 个答案:

答案 0 :(得分:1)

您可以将输入流用于此目的。服务器端代码将如下面的代码

@POST
public Response processProtoRequest(@Context HttpServletRequest req) {
          ProtoRequest protoRequestObj = ProtoRequest.parseFrom(req.getInputStream());
          ///process  protoRequestObj and convert into byte arry and send to clinet
            return  Response.ok(protoRequestObj.toByteArray(),
                        MediaType.APPLICATION_OCTET_STREAM).status(200).build();

}

客户端将如下所示:

   ProtoRequest protoRequestObj = ProtoRequest.newBuilder(). //protocol buffer object
          setSessionId(id).
          setName("l070020").
          build();

       DefaultHttpClinet httpClinet = new DefaultHttpClinet();
       HttpPost request = new HttpPost("http://localhost:8080/maven.work/service/mainServices/protoRequest");
    request.addHeader("accept","application/octet-stream");
    request.setEntity(protoRequestObj.toByteArray());  
    HttpResponse response = httpClient.execute(request);

答案 1 :(得分:1)

我编写了一个Step by Step tutorial,关于如何在Web服务中生成/使用协议缓冲流,使用Jersey作为客户端JAX-RS实现。我希望它会对你有所帮助。 :)

服务器端:

@GET
@Path("/{galaxy}")
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getInfo(@PathParam("galaxy") String galaxyName){

    if(StringUtils.equalsIgnoreCase("MilkyWay", StringUtils.remove(galaxyName, ' '))){

        // The following method would call the DTO Galaxy builders.
        Galaxy milkyWay = MilkyWayFactory.createGalaxy();

        // This is the important line for you where where the generated toByteArray() method takes responsibility of serializing the instance into a Protobuf format stream
        return Response.ok(milkyWay.toByteArray(),MediaType.APPLICATION_OCTET_STREAM).status(200).build();
    }

    return Response.status(Status.NOT_FOUND).build();
}

客户端:

String serverContext = "learning-protobuf3-ws-service";
String servicePath = "ws/universe/milkyway";
String serviceHost = "localhost";
Integer servicePort = 8080;

javax.ws.rs.client.Client client = javax.ws.rs.client.ClientBuilder.newClient();

javax.ws.rs.client.WebTarget target = client.target("http://"+serviceHost+":"+servicePort+"/"+serverContext)
                                            .path(servicePath);


InputStream galaxyByteString = target.request(MediaType.TEXT_HTML)
        .header("accept",MediaType.APPLICATION_OCTET_STREAM)
        .get(InputStream.class);

Galaxy galaxy = Galaxy.parseFrom(IOUtils.toByteArray(galaxyByteString));

答案 2 :(得分:0)

您可以使用base64对SerializeToString的结果进行编码。