协议消息标记具有无效的线路类型

时间:2012-10-15 12:39:35

标签: buffer protocols protocol-buffers

我的应用程序通过protobuf从服务器向客户端发送数据。 当我在客户端反序列化已发送的有效负载时,eclipse会抛出follogwing类型:

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;

如您所见,服务器使用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数据。

1 个答案:

答案 0 :(得分:3)

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

相关问题