我已经编写了一个关于如何在 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));