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

What is the function of OkHttp in Android

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about the role of OkHttp in Android. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

HTTP is a common network way to exchange data and media in modern applications. Efficient use of HTTP can make resources load faster and save bandwidth. OkHttp is an efficient HTTP client with the following default features:

Support for HTTP/2, allowing all requests with the same host address to share the same socket connection

Connection pooling reduces request latency

Transparent GZIP compression reduces the size of response data

Cache the response content to avoid some completely repetitive requests

When there is a network problem, OkHttp still sticks to its duty, it will automatically recover the general connection problem, if your service has more than one IP address, when the first IP request fails, OkHttp will alternately try other IP,OkHttp you configure to initialize a new connection using modern TLS technology (SNI, ALPN), and fall back to TLS 1.0 when the handshake fails.

Don't talk too much nonsense and get to the point right away.

To use OkHttp, you must first configure the gradle environment, or you can download the jar package and add it to your own project

Let's use OkHttp in detail.

First draw the layout, which is simply drawn here, with a button and a scrollable text box added to the layout

Then go back to MainActivity, find the control and set the relevant properties, here to recommend a gadget (LayoutCreator), do not have to write findViewById (), free your hands.

First, click File to open the settings interface.

Click the plug-in, and then click Browse repositorie

Search for LayoutCreator in the pop-up form. I have downloaded it here, so I don't have a download button. You can download it yourself. There is some introduction to the plug-in on the right, so you can have a look at it.

After downloading, restart Android Studio and you can see the plug-in here.

How to use it? It's simple, double-click to select the layout parameter first.

Then click Code, continue to click LayoutCreator, the code will be automatically generated, is not very convenient? The premise is that your control must have id, and code cannot be generated automatically without an id value.

Having said so much, how do I feel beside the point? please forgive me for wanting to share the plug-in's heart with you and get back to the point.

Network requests are nothing more than get requests and post requests. Here's how OkHttp makes get and post requests.

GET request

OkHttpClient client = new OkHttpClient (); String run (String url) throws IOException {Request request = new Request.Builder (). Url (url). Build (); Response response = client.newCall (request). Execute (); if (response.isSuccessful ()) {return response.body (). String ();} else {throw new IOException ("Unexpected code" + response);}}

Some friends may not be able to walk here. Check the log and find out.

Don't panic when you encounter a problem. You can only grow in the process of solving the problem. In fact, the reason for this problem is that OkHttp's library depends on the jar package okio.jar, which can be downloaded from GitHub:

To continue with the GET request, after sending the request using the execute () method, it will enter the blocking state until a response is received

Of course, OkHttp also encapsulates asynchronous request methods, which handle responses in callbacks

OkHttpClient client = new OkHttpClient.Builder (). ReadTimeout (5, TimeUnit.SECONDS). Build (); Request request = new Request.Builder (). Url ("http://www.baidu.com"). Get (). Build (); Call call = client.newCall (request)) Call.enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {System.out.println ("Fail");}

@ Override public void onResponse (Call call, Response response) throws IOException {

System.out.println (response.body () .string ())

})

Post method to make a synchronous request

String okPost (String url, String json) throws IOException {MediaType JSON = MediaType.parse ("application/json; charset=utf-8"); RequestBody body = RequestBody.create (JSON, json); Request request = new Request.Builder () .url (url) .post (body) .build (); Response response = client.newCall (request). Execute (); return response.body (). String ();}

Asynchronous request for post method

OkHttpClient okHttpClient = new OkHttpClient (); / / parameters in Form form format are passed FormBody formBody = new FormBody .Builder () .add ("username", "androidxx.cn") / / set parameter name and parameter value .build () Request request = new Request .Builder () .post (formBody) / / the parameter of the Post request is passed .url (Config.LOCALHOST_POST_URL) .build (); okHttpClient.newCall (request) .enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {}

@ Override public void onResponse (Call call, Response response) throws IOException {/ / this method runs in a child thread and cannot UI in this method. String result = response.body (). String (); Log.d ("androixx.cn", result); response.body (). Close ();}}). After reading the above, do you have any further understanding of the role of OkHttp in Android? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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

Internet Technology

Wechat

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

12
Report