Let's teach you how to use ProtoBuf to make network requests on Android through gRPC service

ProtoBuf-gRPC-Android

Teach you how to use ProtoBuf to make network requests on android through gRPC service.

If you are interested, please click Project address See it!

brief introduction

ProtoBuf

>Google published a set of open source coding rules, based on the binary stream serialization transmission, which can be converted into a variety of programming languages, almost covering all the mainstream programming languages on the market, is currently recognized as a very efficient serialization technology.

Github homepage of ProtoBuf: https://github.com/protocolbuffers/protobuf

gRPC

>Grpc is a high performance, open source and general RPC framework, which is designed for mobile and HTTP/2. Currently, C, Java and Go languages are available, which are grpc, grpc Java and grpc Go respectively. Grpc is designed based on HTTP/2 standard, which brings some features such as bidirectional flow, flow control, header compression, and multiple multiplexing requests over a single TCP connection. These features make it perform better on mobile devices, save power and space. Grpc, developed by google, is a language neutral, platform neutral, open source remote procedure call system.

Github home page of gRPC(Java): https://github.com/grpc/grpc-java

Why use ProtoBuf and gRPC

>In short, ProtoBuf is like the medium of information transmission, similar to the json we usually use, while grpc is the channel to transmit them, similar to the socket we often use.

ProtoBuf and json

If we can summarize the difference between ProtoBuf and JSON in one sentence, it is: for large files with more information storage, the efficiency of ProtoBuf writing and parsing is significantly higher, while the readability of JSON format is obviously better. There is a piece of data on the Internet for the performance difference between protobuf and JSON:

JSON

A total of 65535 Data records are written to the file, and the test results are as follows:
The generated file size is 23733k.
The time to generate the file is 12.80 seconds.
The time to parse from this file is 11.50 seconds.

ProtoBuf

A total of 65535 Data records are written to the file, and the test results are as follows:
The generated file size is 3760k.
The time to generate the file is 0.08 seconds.
The time to parse from this file is 0.07 seconds.

gRPC

As a highly recommended distributed network architecture by google, it is designed based on HTTP 2.0 standard and uses ProtoBuf as serialization tool to perform better on mobile devices, save power and space. It's made by google, with reliable quality.

How to use

For such a foreign open source framework, it is recommended that you read the official documents first, and then the domestic articles, so that it is not easy to be misled.

Official course

Official example

Environmental configuration

1. First, download and install the Protobuf Support plug-in, as shown in the following figure:

2. Add the protobuf gradle plugin plug-in to the buildscript of build.gradle in the root directory of the project:

buildscript {
    ...
    dependencies {
        ...
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.6"
    }
}

3. Then configure it in build.gradle of application Module as follows

apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf' //Reference to protobuf gradle plugin plug-in

android {
    ...

    lintOptions {
        abortOnError false
        disable 'GoogleAppIndexingWarning', 'HardcodedText', 'InvalidPackage'
        textReport true
        textOutput "stdout"
    }
}

protobuf {
    protoc { artifact = 'com.google.protobuf:protoc:3.6.1' }
    plugins {
        javalite { artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0" }
        grpc { artifact = 'io.grpc:protoc-gen-grpc-java:1.19.0' // CURRENT_GRPC_VERSION
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.plugins {
                javalite {}
                grpc { // Options added to --grpc_out
                    option 'lite' }
            }
        }
    }
}

dependencies {
    //protobuf
    implementation 'io.grpc:grpc-okhttp:1.19.0'
    implementation 'io.grpc:grpc-protobuf-lite:1.19.0'
    implementation 'io.grpc:grpc-stub:1.19.0'
    implementation 'javax.annotation:javax.annotation-api:1.2'
}

4. Finally, put your. Proto protocol file in the src/main/proto / folder, and click build to compile. If the following figure appears, the environment configuration is successful!

Ordinary request

Be sure to run the request in the demo before testing it Server code.

1. Build Channel

/**
 * Build a common Channel
 *
 * @param host Host service address
 * @param port port
 * @return
 */
public static ManagedChannel newChannel(String host, int port) {
    return ManagedChannelBuilder.forAddress(host, port)
            .usePlaintext()
            .build();
}

2. Build service request API proxy

//Building channels
final ManagedChannel channel = gRPCChannelUtils.newChannel(host, port);
//Build service api proxy
mStub = GreeterGrpc.newStub(channel);

3. Build request entity

//HelloRequest is an automatically generated entity class
HelloRequest request = HelloRequest.newBuilder().setName(message).build();

4. Execution request

//Request for
mStub.sayHello(request, new SimpleStreamObserver<helloreply>() {
    @Override
    protected void onSuccess(HelloReply value) {
        tvGrpcResponse.setText(value.getMessage());
        btnSend.setEnabled(true);
    }
    @MainThread
    @Override
    public void onError(Throwable t) {
        super.onError(t);
        tvGrpcResponse.setText(Log.getStackTraceString(t));
        btnSend.setEnabled(true);
    }
    @Override
    public void onCompleted() {
        super.onCompleted();
        gRPCChannelUtils.shutdown(channel); //Close channel
    }
});

Https request

Compared with the normal request, the first step is to set up a channel differently. The CA certificate needs to be set, and the other steps are the same.

/**
 * Building a SSLChannel
 *
 * @param host         Host service address
 * @param port         port
 * @param authority    domain name
 * @param certificates certificate
 * @return
 */
public static ManagedChannel newSSLChannel(String host, int port, String authority, InputStream... certificates) {
    HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(certificates);
    return OkHttpChannelBuilder.forAddress(host, port)
            //overrideAuthority is very important, you must set the call
            .overrideAuthority(authority)
            .sslSocketFactory(sslParams.sSLSocketFactory)
            .build();
}

Expanding reading

WeChat official account

</helloreply>

Keywords: Mobile Google JSON Java Gradle

Added by Zeradin on Tue, 25 Feb 2020 15:06:29 +0200