Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement OkHttp request in Android

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to implement OkHttp request in Android", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let Xiaobian take you to learn "How to implement OkHttp request in Android"!

OkHttp is currently a very popular network library, supports HTTP/2, allows all requests from the same host address to share the same socket connection, connection pooling reduces request latency, transparent GZIP compression reduces response data size, caches response content, and avoids some completely duplicate requests.

Before we get started, we should first understand the following core classes:

OkHttpClient: Client Object

Request: Access request, Post request needs to include RequestBody

RequestBody: Request data, used in Post requests

Response: Response result of network request

MediaType: data type, used to indicate that the data is json, image, pdf and other series of formats

client.newCall(request).execute(): synchronous request method

client.newCall(request).enqueue(Callback callBack): asynchronous request method, but Callback is executed in child thread, so UI update operation cannot be performed here

OkHttpClient

private OkHttpClient mHttpClient = null; private void initHttpClient() { if (null == mHttpClient) { mHttpClient = new OkHttpClient.Builder() .readTimeout(5, TimeUnit.SECONDS)//Set read timeout .writeTimeout(5,TimeUnit.SECONDS)////Set write timeout .connectTimeout(15,TimeUnit.SECONDS)//Set connection timeout .retryOnConnectionFailure(true)//whether to automatically reconnect .build(); } }

When using OkHttp to request the network, you need to obtain an OkHttp client object OkHttpClient. OkHttpClient can be created directly by new, or by OkHttpClient static internal class Builder. The most common way for daily development is to build.(Builder mode + chain call) to create, static internal Builder provides many methods, such as readTimeout for read time, writeTimeout for write time, connectTimeout for connection timeout and retryOnConnectionFailure for reconnection, etc. With OkHttpClient, synchronous and asynchronous requests to the network can be made.

synchronization request

private void synRequest() { Request request=new Request.Builder() .url("http://www.baidu.com") .get() .build(); Call call=mHttpClient.newCall(request); try { Response response=call.execute(); System.out.println(request.body().toString()); } catch (IOException e) { e.printStackTrace(); } }

When making a network request, you need to create a request object first. The Request object is also created by building. In the static internal class Builder of Request, the method of setting the request address, request mode and request header is defined.

Then create a Call object, which can be understood as a bridge between Request and Response. Finally, read Response through the execute method of Call object.

The three steps to summarize a synchronization request are as follows:

Create OkHttpClient and Request objects.

Encapsulate the Request object into a Call object.

Call the execute() method of Call to send a synchronization request.

Note: OkHttp synchronization request will block the current thread, so it cannot be requested in the UI thread, you need to open the child thread, send the request in the child thread.

asynchronous request

private void asyRequest() { final Request request=new Request.Builder() .url("http://www.baidu.com") .get() .build(); Call call=mHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println(request.body().toString()); } }); }

The first two steps of asynchronous request and synchronous request are the same: create OkHttpClient and Request object and encapsulate Request object into Call object, execute asynchronous request through enqueue method of Call object, enqueue passes a Callback object, Callback provides two callback methods, success and failure respectively.

The three steps to summarize asynchronous requests are as follows:

Create OkHttpClient and Request objects.

Encapsulate the Request object into a Call object.

Call the enqueue method of Call to make asynchronous requests.

Note: OkHttp asynchronous request, where two callback methods onResponse and onFailure are executed in the worker thread, the execution result can be sent through the Handler.

At this point, I believe that everyone has a deeper understanding of "how to implement OkHttp requests in Android," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report