5

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

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

protoRequest.build.toByteArray()

在服务器中,我需要 c

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

这是正确的做法吗?

谢谢

大卫

4

3 回答 3

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);
于 2012-11-28T18:03:02.397 回答
1

我已经编写了一个关于如何在 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));
于 2016-09-29T09:57:09.433 回答
0

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

于 2010-10-07T00:20:59.527 回答