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 use OkHttp

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

Share

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

This article mainly shows you "how to use OkHttp", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use OkHttp" this article.

Preface

First, take a look at the evolution diagram of network requests in Android:

HttpURLConnection,Apache HTTP Client,Volley to the present OKHttp, it can be said that there is a day outside the sky, there are people outside the world. Why is OKHttp so popular? I believe the following introduction will tell you the answer.

A brief introduction to OKHttp

First of all, give the project address of OKHttp: https://github.com/square/okhttp

Android provides us with two ways to interact with HTTP: HttpURLConnection and Apache HTTP Client, although both support HTTPS, stream upload and download, configuration timeout, IPv6 and connection pooling, which is sufficient to meet our various HTTP requests. But using HTTP more efficiently can make your application run faster and save traffic. And the OkHttp library is created for this reason. OkHttp is an efficient HTTP library:

1. Support for SPDY, sharing the same Socket to handle all requests from the same server

two。 If SPDY is not available, the request delay is reduced by connecting to the pool

3. Seamless support for GZIP to reduce data traffic

1. Cache response data to reduce duplicate network requests

two。 General get request

3. General post request

4. File upload based on Http

5. File download

6. Load Picture

7. Support request callback and return objects and object collections directly

8. Support the retention of session

OkHttp automatically recovers from many common connection problems. If your server is configured with multiple IP addresses, when * IP connections fail, the next IP will be tried automatically. OkHttp also handles proxy server issues and SSL handshake failures. (concurrent) there is no need to rewrite the network code in your program using OkHttp. OkHttp implements almost the same API as java.net.HttpURLConnection. If you use Apache HttpClient, OkHttp also provides a corresponding okhttp-apache module. As you can see from the brief introduction above, although it will not be much simpler in programming, some internal features of OKHttp can help us automatically complete some very complex operations. I personally think that the selling point of * * is to greatly save users' traffic.

Basic use of OKHttp

1. Introduce the dependent library of CardView into Gradle.

Compile 'com.squareup.okhttp:okhttp:3.8.0'

2. Before using OKHttp, you should first understand the following core classes and their functions.

OkHttpClient client object

Request is a request for access in OkHttp. RequestBody needs to be included in the Post request.

Builder is an auxiliary class that is used for production objects

Response is the response in OkHttp. Whether the return is successful or not can be obtained in the response, and the data is returned.

MediaType data type, used to indicate a series of formats such as JSON

RequestBody request data, used in Post requests

Client.newCall (request). Execute () is a synchronous request method

Client.newCall (request) .enqueue (Callback callBack) is an asynchronous request method, but the code in the Callback is executed in the child thread, so the UI cannot be updated.

3. Basic steps for using OKHttp (take POST to fetch JSON data from the server as an example)

To create an OkHttpClient object, the official documentation requires us to use singleton mode, which will be mentioned later when encapsulating OKHttp.

If it is a post request, you need to create a RequestBody object through FormEncodingBuilder and specify the parameters that need to be passed in by post. Get requests are not used.

Create a Request object, which is the request object, and you need to specify URL. The RequestBody object needs to be specified when the post request is made, but not the get request.

Call the newCall method of OkHttpClient, pass in the Request object, and then execute the execute or enqueue method, the difference of which was mentioned above. The onResponse method in CallBack can do what you need to do. The parameter of onResponse callback is response. In general, if we want to get the returned string, we can get it through response.body (). String (); if we want to get the returned binary byte array, call response.body () .bytes () If you want to get the returned inputStream, call response.body (). ByteStream () to see this, you may be surprised that you can still get the returned inputStream. If you see this, you can at least realize that large file downloads are supported, and with inputStream, we can write files through IO. However, it also shows that the thread of onResponse execution is not a UI thread. Indeed, if you want to manipulate the control, you still need to use handler and so on.

OkHttpClient client = new OkHttpClient (); RequestBody body = new FormEncodingBuilder () .add ("type", "1") .build (); Request request = new Request.Builder () .url (Constants.URL_BANNER) .post (body) .build () Client.newCall (request) .enqueue (new Callback () {@ Override public void onFailure (Request request, IOException e) {} @ Override public void onResponse (Response response) throws IOException {if (response.isSuccessful ()) {android.os.Message msg = new Message (); msg.what = 1 Msg.obj = response.body () .string (); mHandler.sendMessage (msg);})

This is just a simple post request, an introduction to getting data from the server, while the get request is simply removing the RequestBody object. As for how to submit data to the server, you can check out the official WIKI (GitHub introduction document) after you are familiar with the basic usage above.

Simple package of OKHttp

Looking back at the above code, imagine that if you write so much repetitive code for each request, it will seriously reduce development efficiency, so you need to encapsulate OKHttp. Encapsulating the code is the basic accomplishment of our most object-oriented programmers, reducing the duplication of code and reducing the difficulty and cost of maintenance.

OKHttp is also encapsulated on GitHub, called OKHttpUtils. But here we do it ourselves, let's learn how to package it. The specific points for attention are as follows:

1. First of all, OKHttp officially requires us to use singleton mode to use OKHttpClient class, so we customize an OKHttpHelper class and use singleton mode.

2. Encapsulate the get and post methods, the main idea is to extract the common code, such as the request method extracted from the code.

3. Disclose some static methods, including get and post methods, etc.

4. Callback base class, which encapsulates the callback of OKHttp. There is a type in this class, which is convenient to use Gson to parse the JSON in the callback. When using Callback, you only need to pass something like Data and List in the generic type to make it easy to use JSON.

5. Since the original callback is not in the main thread, we need to use Handler to put the callback into the main thread.

The rest can refer to the code and have detailed comments.

/ * this class is used to assist OKHttp * / public class OkHttpHelper {/ * to use OkHttpClient * / private static OkHttpHelper mOkHttpHelperInstance; private static OkHttpClient mClientInstance; private Handler mHandler; private Gson mGson in singleton mode / * Singleton mode, private constructor, some initialization is performed in the constructor * / private OkHttpHelper () {mClientInstance = new OkHttpClient (); mClientInstance.setConnectTimeout (10, TimeUnit.SECONDS); mClientInstance.setReadTimeout (10, TimeUnit.SECONDS); mClientInstance.setWriteTimeout (30, TimeUnit.SECONDS); mGson = new Gson () MHandler = new Handler (Looper.getMainLooper ()) } / * get an instance * * @ return * / public static OkHttpHelper getinstance () {if (mOkHttpHelperInstance = = null) {synchronized (OkHttpHelper.class) {if (mOkHttpHelperInstance = = null) {mOkHttpHelperInstance = new OkHttpHelper () } return mOkHttpHelperInstance;} / * encapsulates a request method, which uses * / public void request (final Request request, final BaseCallback callback) {/ / things done before the request, such as pop-up dialog boxes and other callback.onRequestBefore (), regardless of post or get methods. MClientInstance.newCall (request) .enqueue (new Callback () {@ Override public void onFailure (Request request, IOException e) {/ / returns failed callbackFailure (request, callback, e) } @ Override public void onResponse (Response response) throws IOException {if (response.isSuccessful ()) {/ / returns a successful callback String resString = response.body () .string () If (callback.mType = = String.class) {/ / if we need to return the String type callbackSuccess (response, resString, callback) } else {/ / if other types are returned, use Gson to parse try {Object o = mGson.fromJson (resString, callback.mType); callbackSuccess (response, o, callback) } catch (JsonParseException e) {e.printStackTrace (); callbackError (response, callback, e) } else {/ / returns error callbackError (response, callback, null);}) * * @ param response * @ param resString * @ param callback * / private void callbackSuccess (final Response response, final Object o) Final BaseCallback callback) {mHandler.post (new Runnable () {@ Override public void run () {callback.onSuccess (response, o)) }) * @ param response * @ param callback * @ param e * / private void callbackError (final Response response, final BaseCallback callback, final Exception e) {mHandler.post (new Runnable () {@ Override public void run () {callback.onError (response)) Response.code (), e) }) * @ param request * @ param callback * @ param e * / private void callbackFailure (final Request request, final BaseCallback callback, final Exception e) {mHandler.post (new Runnable () {@ Override public void run () {callback.onFailure (request, e)) Public get method * * @ param url * @ param callback * / public void get (String url, BaseCallback callback) {Request request = buildRequest (url, null, HttpMethodType.GET); request (request, callback) Public post method * * @ param url * @ param params * @ param callback * / public void post (String url, Map params, BaseCallback callback) {Request request = buildRequest (url, params, HttpMethodType.POST); request (request, callback) } / * build request object * * @ param url * @ param params * @ param type * @ return * / private Request buildRequest (String url, Map params, HttpMethodType type) {Request.Builder builder = new Request.Builder (); builder.url (url) If (type = = HttpMethodType.GET) {builder.get ();} else if (type = = HttpMethodType.POST) {builder.post (buildRequestBody (params));} return builder.build () } / * build the body * * @ param params * @ return * / private RequestBody buildRequestBody (Map params) {FormEncodingBuilder builder = new FormEncodingBuilder () of the request object through the key-value pair of Map If (params! = null) {for (Map.Entry entity: params.entrySet ()) {builder.add (entity.getKey (), entity.getValue ());}} return builder.build () } / * this enumeration is used to indicate which submission method * / enum HttpMethodType {GET, POST}}

Callback encapsulation

Package com.nan.cnshop.http; import com.google.gson.internal.$Gson$Types; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type;/** * basic callback * / public abstract class BaseCallback {/ * type is used to facilitate JSON parsing * / public Type mType / * convert type to the corresponding class. You don't have to read it here. * * @ param subclass * @ return * / static Type getSuperclassTypeParameter (Class subclass) {Type superclass = subclass.getGenericSuperclass (); if (superclass instanceof Class) {throw new RuntimeException ("Missing type parameter.");} ParameterizedType parameterized = (ParameterizedType) superclass; return $Gson$Types.canonicalize (parameterized.getActualTypeArguments () [0]) } / * get type's class * / public BaseCallback () {mType = getSuperclassTypeParameter (getClass ()) during construction; * / public abstract void onRequestBefore () is called before request. / * @ param request * @ param e * / public abstract void onFailure (Request request, Exception e); / * @ param response * @ param t * / public abstract void onSuccess (Response response, T t) when the request is successful and there are no errors Called when the request is successful but has errors, such as Gson parsing errors, * * @ param response * @ param errorCode * @ param e * / public abstract void onError (Response response, int errorCode, Exception e);}

Use after OKHttp encapsulation

As shown in the following code. First get a singleton of OkHttpHelper, and then call the get method. Because you inherit Gson, you need to pass the data type corresponding to JSON in the generics of BaseCallback, which is List. * do what we want to do in the onSuccess method.

MHttpHelper=OkHttpHelper.getinstance (); mHttpHelper.get (Constants.URL_BANNER, new BaseCallback () {@ Override public void onRequestBefore () {} @ Override public void onFailure (Request request, Exception e) {} @ Override public void onSuccess (Response response, List banners) {initBanners (banners);} @ Override public void onError (Response response, int errorCode, Exception e) {}})

Do you think that the use of OKHttp becomes very simple after encapsulation? this is the power of encapsulation. Well, that's all for today's notes.

The above is all the contents of this article "how to use OkHttp". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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