Android network framework OKHttp

Posted by johnthedeveloper on Fri, 03 Jan 2020 21:29:32 +0100

Summary

OKhttp is an open source project of network request. Android network request lightweight framework supports file upload and download, https, and contributed by mobile payment Square company.

rely on

compile 'com.squareup.okhttp3:okhttp:3.8.1'

Get request

Send synchronization request by Get

OkHttpClient okHttpClient;
Request request;
okHttpClient = new OkHttpClient();
request = new Request.Builder()
        .url("http://www.baidu.com")//Request interface,If you need to splice parameters behind the interface,as www.baidu.com?name=zhangsan&sex=18
        .build();
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Response response = call.execute();//obtain Response object
            if(response.isSuccessful()){//Judge whether to respond
                Log.d("response ","Response code"+response.code());//Return http Response code of protocol
                Log.d("response ","Return content"+response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

Send asynchronous request by Get

OkHttpClient okHttpClient;
Request request;
okHttpClient = new OkHttpClient();
request = new Request.Builder()
        .url("http://www.baidu.com")//Request interface. If parameters need to be spliced behind the interface, such as www.baidu.com?name=zhangsan&sex=18
        .build();
final Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
     @Override
     public void onFailure(Call call, IOException e) {

     }

     @Override
     public void onResponse(Call call, Response response) throws IOException {
            if(response.isSuccessful()){//Judge whether to respond
                Log.d("response ","Response code"+response.code());//Return http Response code of protocol
                Log.d("response ","Return content"+response.body().string());
            }
     }
 });

Post request

FormBody passes key value pair parameters

FormBody body = new FormBody.Builder() //Create information subject
        .add("name", name)
        .add("sex", department)
        .add("possword", post)
        .add("data", formatter.format(getData()))
        .build();

RequestBody passes the Json or File object

//transmit Json object
MediaType JSON = MediaType.parse("application/json; charset=utf-8");//Specify data type as json Object,
String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"Li Si\"}";//json data.
RequestBody body = RequestBody.create(JSON, josnStr);

//transmit File object
MediaType fileType = MediaType.parse("File/*");//Specify data type as file Object,
File file = new File(path);//file object
RequestBody body = RequestBody.create(fileType , file );

MultipartBody passing key value pair object and File object

MultipartBody multipartBody =new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("groupId",""+Id)//Add key value pair parameter
        .addFormDataPart("file",file.getName(),RequestBody.create(MediaType.parse("file/*"), file))//Add files
        .build();

Post synchronous / asynchronous request

//FormBody delivers data,Post Synchronous request
OkHttpClient okHttpClient;
okHttpClient = new OkHttpClient();
FormBody body = new FormBody.Builder() //Create information subject
        .add("name", name)
        .add("sex", department)
        .add("possword", post)
        .add("data", formatter.format(getData()))
        .build();
Request requset = new Request.Builder()
        .url("url")
        .post(body)
        .build();
final Call call = okHttpClient.newCall(requset);
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Response response = call3.execute();//obtain Response object
            if(response.isSuccessful()){//Judge whether to respond
                Log.d("response ","Response code"+response.code());//Return http Response code of protocol
                Log.d("response ","Return content"+response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

//RequestBody() passes the data,Post Asynchronous request
OkHttpClient okHttpClient;
okHttpClient = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");//The data type is json Format,
String jsonStr = "{\"username\":\"lisi\",\"nickname\":\"Li Si\"}";//json data.
RequestBody body = RequestBody.create(JSON, jsonStr);
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .post(body)
        .build();
final Call call = okHttpClient.newCall(requset);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if(response.isSuccessful()){//Judge whether to respond
            Log.d("response ","Response code"+response.code());//Return http Response code of protocol
            Log.d("response ","Return content"+response.body().string());
        }
    }
});

General request overview

Through the above code, the Get or Post Request needs to instantiate the OkHttpClient object, create the Request with Request and send the Request with Response, and the Call scheduler receives the returned content.

The Call object has two modes: Call. Execute() synchronous mode and call.enqueue() asynchronous mode.

Synchronization is in the main thread operation, so you need to start the sub thread operation. Asynchrony is the Response returned by the CallBack, which is operated in a sub thread, but the CallBack's onFailure() and onResponse() are still in the sub thread.

Respine. Body() is also in the sub thread. You need to receive the content before calling the main thread operation.

Note that response.body() can only be called once, because it is a read operation of the output stream, while a read-write operation is only received once, and null will be returned the second time.

Set network timeout

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)//Set timeout
    .readTimeout(10, TimeUnit.SECONDS)//Set read timeout
    .writeTimeout(10, TimeUnit.SECONDS);//Set write timeout

Interceptor of OKHttp

 Reprint - on the interceptor of OKHttp

OKHttp download file

 Reprint - OKHttp Download File instance

Topics: Android JSON OkHttp network