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



我的应用程序通过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 提供的构建器模式来设置必要的字符串。然后将数据序列化为 byte[],并通过 protobuf 发送回客户端。

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

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

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

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

相关内容

最新更新