3

我的应用程序通过 protobuf 从服务器向客户端发送数据。当我在客户端 Eclipse 上反序列化发送的有效负载时,会引发以下类型的期望:

Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.

当我调用“parseFrom()”时会发生预期。我知道在大多数情况下,错误在于语法错误的 protobuf 文件。因此,我希望在这里发布 protobuf 定义就足够了:

   package protobuf;

       option java_package = "com.carproject.abs.demo.protobuf";
       option java_outer_classname = "DesktopDevice_getCarsResponse";

    message CARS {

        required int64 carid = 1;
        required string carname = 2;

        message Carinformation {
            required string street = 1;
            required string postalcode = 2;
            required string city = 3;
            required string country = 4;
            required string cartimezoneid = 5;
        }

        message Right {
            optional string name = 1;
            optional int32 type = 2;
            optional int32 service = 3;
        }

        message PropertyType {
            optional string name = 1;
            optional string value = 2;
        }

        repeated Carinformation carinformation = 3; 
        repeated Right carrights = 4;
        repeated PropertyType carproperties = 5;
        repeated string inoid = 6;
    }

这是显示数据如何在服务器端写入的代码:

// carObj returns the necessary Strings
CAR carObj = car.getCAR();

Builder newBuilder = DesktopDevice_getCarResponse.CAR.newBuilder();

newBuilder.setCarid( carObj.getCARID() );
newBuilder.setCarname( carObj.getCARNAME());

// hardcoded values here
newBuilder.getCarinformationBuilder(1).setStreet( carObj.getCARNFORMATION().getSTREET() );
newBuilder.getCarinformationBuilder(1).setPostalcode( carObj.getCARINFORMATION().getPOSTALCODE() );
newBuilder.getCarinformationBuilder(1).setCity( carObj.getCARINFORMATION().getCITY() );
newBuilder.getCarinformationBuilder(1).setCountry( fleetObj.getCARINFORMATION().getCOUNTRY() );
newBuilder.getCarinformationBuilder(1).setCartimezoneid( fleetObj.getCARINFORMATION().getCARTIMEZONEID() );

byte[] responsePayload = newBuilder.build().toByteArray();
RestServerResponseMessage responseMsg = new RestServerResponseMessage( requestMsg.getRequestId(), responsePayload, "XML");
return responseMsg;

如您所见,Server 使用 protobuf 提供的 Builder 模式来设置必要的字符串。然后将数据序列化为 byte[] 并通过 protobuf 发送回客户端。

这是我尝试解析数据的客户端代码。

HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();
        CAR car = DesktopDevice_getCarsResponse.CARS.parseFrom(instream);
        }

调用 .parseFrom 时会引发异常。服务器代码和 carObj 工作正常。我已经在我的程序中成功发送了 protobuf 数据。

4

1 回答 1

3

Base64.getEncoder.encode(protoMsg.toByteArray)在服务器上使用。并使用Base64.getDecoder.decode(receivedArray[Bytes]). 在线发送的数据应始终进行编码和解码

于 2015-07-29T07:38:24.573 回答