BaseOkHttp V3

Github

Github.com/kongzue/Bas…




Introduction to the

  • BaseOkHttp V3 is based on BaseOkHttp V2(github.com/kongzue/Bas… Based on a library that can quickly create commonly requested links.
  • This library has its own OkHttp library, and its associated OKIO library package name modification and encapsulation, so it will not affect the other versions of OkHttp library in your project, and will not cause conflicts.
  • If the request comes from an Activity, it is automatically returned to the main thread after the request ends, with no additional processing required.
  • Provides a uniform return listener (ResponseListener) to handle returned data, avoiding repeated code bloat.
  • Powerful global methods and events make your requests handy.

How Maven repositories or Gradle are referenced

Maven repositories:

<dependency> <groupId>com.kongzue.baseokhttp_v3</groupId> <artifactId>baseokhttp_v3</artifactId> The < version > 3.0.2 < / version > <type>pom</type>
</dependency>
Copy the code

Gradle:

Add a reference to dependencies{}

implementation 'com. Kongzue. Baseokhttp_v3: baseokhttp_v3:3.0.2'
Copy the code

A trial version can be downloaded at fir. Im /BaseOkHttp

General request

BaseOkHttp V3 provides two request forms, as shown in the following example:

Create a request as a parameter:

progressDialog = ProgressDialog.show(context, "One moment, please."."In request...");
HttpRequest.POST(context, "Http://your interface address", new Parameter().add("page"."1"), new ResponseListener() {
    @Override
    public void onResponse(String response, Exception error) {
        progressDialog.dismiss();
        if (error == null) {
            resultHttp.setText(response);
        } else {
            resultHttp.setText("Request failed");
            Toast.makeText(context, "Request failed", Toast.LENGTH_SHORT).show(); }}});Copy the code

For normal requests, use httprequest.post (…). The httprequest.get (…) method creates a POST request directly. You can create a GET request, and optionally add a header request header:

HttpRequest.POST(Context context, String url, Parameter headers, Parameter parameter, ResponseListener listener);
HttpRequest.GET(Context context, String url, Parameter headers, Parameter parameter, ResponseListener listener);
Copy the code

Or you can create the request in streaming code:

progressDialog = ProgressDialog.show(context, "One moment, please."."In request...");
HttpRequest.build(context,"Http://your interface address")
        .addHeaders("Charset"."UTF-8")
        .addParameter("page"."1")
        .addParameter("token"."A128")
        .setResponseListener(new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("Request failed");
                    Toast.makeText(context, "Request failed", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .doPost();
Copy the code

There is only one callback listener returned, in which the error parameter should be nulled. If the error parameter is not empty, the request fails; otherwise, the request succeeds. The data after successful request is stored in the response parameter.

The main purpose of putting the request success and failure in a callback is to facilitate code that needs to be executed regardless of the request success or failure. For example, the progressDialog waiting dialog in the above code needs to be closed (dismiss), which is more convenient to write.

Json request

Httprequest.jsonpost (…) : httprequest.jsonPost (…) Method to create a JSON request.

In the JSON request, the parameters are text types. The request can be created in the following way:

progressDialog = ProgressDialog.show(context, "One moment, please."."In request...");
HttpRequest.JSONPOST(context, "Http://your interface address"."{\"key\":\"DFG1H56EH5JN3DFA\",\"token\":\"124ASFD53SDF65aSF47fgT211\"}", new ResponseListener() {
    @Override
    public void onResponse(String response, Exception error) {
        progressDialog.dismiss();
        if (error == null) {
            resultHttp.setText(response);
        } else {
            resultHttp.setText("Request failed");
            Toast.makeText(context, "Request failed", Toast.LENGTH_SHORT).show(); }}});Copy the code

For Json requests, use httprequest.jsonPost (…). To quickly create a Json request, optionally add a header request header:

HttpRequest.JSONPOST(Context context, String url, Parameter headers, String jsonParameter, ResponseListener listener)
Copy the code

Requests can also be created using streaming code:

progressDialog = ProgressDialog.show(context, "One moment, please."."In request...");
HttpRequest.build(context,"Http://your interface address")
        .setJsonParameter("{\"key\":\"DFG1H56EH5JN3DFA\",\"token\":\"124ASFD53SDF65aSF47fgT211\"}")
        .setResponseListener(new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("Request failed");
                    Toast.makeText(context, "Request failed", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .doPost();
Copy the code

Json requests can only be made as POST if doGet() is executed; Methods are also issued as POST.

File upload

To use File upload, you need to pass in a File of type File as a Parameter. You can also pass in parameters of other text types.

Once the parameters are passed into the file, the request must be of type POST, even if httprequest.get (…) is called. It is also issued as a POST request.

The sample code is as follows:

progressDialog = ProgressDialog.show(context, "One moment, please."."In request...");
HttpRequest.POST(context, "Http://your interface address", new Parameter()
                         .add("key"."DFG1H56EH5JN3DFA")
                         .add("imageFile1", file1)
                         .add("imageFile2", file2)
        , new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("Request failed");
                    Toast.makeText(context, "Request failed", Toast.LENGTH_SHORT).show(); }}});Copy the code

Requests can also be created using streaming code:

HttpRequest.build(context,"Http://your interface address")
        .addHeaders("Charset"."UTF-8")
        .addParameter("page"."1")
        .addParameter("imageFile1", file1)
        .addParameter("imageFile2", file2)
        .setResponseListener(new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("Request failed");
                    Toast.makeText(context, "Request failed", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .doPost();
Copy the code

The default mediaType for uploaded files is “image/ PNG “, which can be changed using the following code:

.setMediaType(MediaType.parse("application/pdf") // Set to PDF typeCopy the code

The type reference is as follows:

content meaning
text/html HTML format
text/plain Plain text format
text/xml XML format
image/gif GIF image format
image/jpeg JPG image format
image/png PNG image format
application/xhtml+xml XHTML
application/xml XML data format
application/atom+xml Atom XML aggregation format
application/json JSON data format
application/pdf PDF format
application/msword Word Document Format
application/octet-stream Binary stream data
multipart/form-data The form data

Additional functionality

Global log

Global log switch (manually enable it by default) :

BaseOkHttp.DEBUGMODE = true;
Copy the code

BaseOkHttp V3 supports enhanced logs. If the output log content is a JSON string, it is automatically formatted for viewing.

When you use BaseOkHttp, you can use the character “>>>” in the Logcat filter to filter logs (the search input box at the top and right of the Logcat log screen).

You can change the Color of each type of log in Android Studio from File -> Settings Editor -> Color Scheme -> Android Logcat. We recommend setting the Color as follows:

Global request address

After setting the global request address, all interfaces can use the relative address directly, for example, setting the global request address:

BaseOkHttp.serviceUrl = "https://www.example.com";
Copy the code

Make a request:

HttpRequest.POST(context, "/femaleNameApi", new Parameter().add("page"."1"), new ResponseListener() {... });Copy the code

So the actual request address is www.example.com/femaleNameA… , more relaxed and convenient to use.

Global Header Request Header

Set the global Header request Header with the following code:

BaseOkHttp.overallHeader = new Parameter()
        .add("Charset"."UTF-8")
        .add("Content-Type"."application/json")
        .add("Accept-Encoding"."gzip,deflate");Copy the code

Global request return interceptor

Use the following code to set the global return data listener interceptor, return true can return the request to continue processing, return false that intercepts will not continue to return the original request for processing;

BaseOkHttp.responseInterceptListener = new ResponseInterceptListener() {
    @Override
    public boolean onResponse(Context context, String url, String response, Exception error) {
        if(error ! = null) {return true;
        } else {
            Log.i("!!!"."onResponse: " + response);
            return true; }}};Copy the code

HTTPS support

  1. Put the SSL certificate file in the assets directory, for example, ssl.crt.
  2. Create the request with the SSL certificate name attached:
BaseOkHttp.SSLInAssetsFileName = "ssl.crt"; .Copy the code

You can use Https request mode.

. In addition, can use BaseOkHttp httpsVerifyServiceUrl = (Boolean) set whether validation request host address and Settings of HttpRequest. ServiceUrl consistently;

Global parameter interceptor

Use the following code to set up the global parameter listener interceptor, which intercepts, modifies, and adds new parameters to all requests.

This method also applies to scenarios where parameters need to be encrypted:

BaseOkHttp.parameterInterceptListener = new ParameterInterceptListener() {
    @Override
    public Parameter onIntercept(Parameter parameter) {
        parameter.add("key"."DFG1H56EH5JN3DFA");
        parameter.add("sign", makeSign(parameter.toParameterString()));
        returnparameter; }}; Private String makeSign(String parameterString){// makeSign... }Copy the code

The request timeout

Set the request timeout (in seconds) with the following code

BaseOkHttp.TIME_OUT_DURATION = 10;
Copy the code

Open source licenses

Copyright Kongzue BaseOkHttp

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except inThe compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed toin writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copy the code

The underlying network request framework used in this project is square.okhttp3 (github.com/square/okht…). For its contribution to open source.

Relevant agreements are as follows:

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except inThe compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed toin writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copy the code

Update log

V3.0.2:

  • New log print request header;
  • Log request parameter print enhancement;
  • Modified OkHttplient creation method and HTTPS authentication ignored when no certificate is set by default.
  • Fixed file upload related bug;

V3.0.1:

  • Fixed some bugs.