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 the OkHttp Network request Framework

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

Share

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

This article mainly introduces "how to use the OkHttp network request framework". In the daily operation, I believe that many people have doubts about how to use the OkHttp network request framework. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the OkHttp network request framework". Next, please follow the editor to study!

1. Introduction of OkHttp

   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 excellent web request framework 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

: @. . @: + @: + @ + @ `@: + @ @ @ `@ @ + @ `@: @ + @ @ @ `@ + @ +` @: @:. @ @ + @. . @ @ `@: @: @ @:

Introduce maven dependencies:

Com.squareup.okhttp3 okhttp ${laster.version}

The OkHttp project has the following modules:

Module content okhttp implementation OkHttp library module okhttp-testsOkHttp library unit test module okhttp-android-support support android platform using OkHttp library module okhttp-apache implementation ApacheHttpClient interface (next version will be deprecated) okhttp-testing-support support module okhttp-urlconnection implementation HttpURLConnection interface (next version will be deprecated) okhttp-ws support WebSocketokhttp-logging-interceptor implementation Logging interceptor okcurl implementation OkCurlmockwebserver script WebServer, used to test HTTP client

The parent module of the OkHttp project mainly contains the following plug-ins:

Plug-in usage maven-compiler-plugin compilation project maven-surefire-plugin execution test maven-javadoc-plugin generation document maven-release-plugin automation project version release maven-checkstyle-plugin detection coding style animal-sniffer-maven-plugin detection code API

Official introduction

Github source code

2. OkHttp basically uses 2.1for Get requests.

It takes only four steps to make an Get request using OkHttp:

Create an okHttpClient object

OkHttpClient client = new OkHttpClient ()

Construct Request object

/ / first, construct a Request object with at least one url. Of course, you can set more parameters through Request.Builder, such as header, method, etc. Request request = new Request.Builder (). Get (). Url ("https://api.github.com/users/dllwh").build();"

Encapsulate Request as Call

/ / construct a Call object through the object of request, which is similar to encapsulating the request into a task Call call = client.newCall (request)

Call synchronous or asynchronous request methods as needed

/ / synchronous call, return Response, need to throw IO exception Response response = call.execute (); if (response.isSuccessful ()) {System.out.println (response.body (). String ());}

> synchronous calls block the main thread until the HTTP response returns. The execute method in OKHTTP is generally not applicable.

/ / execute the code of the request call.enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {} @ Override public void onResponse (Call call, final Response response) throws IOException {/ / http response line asynchronously, and return 200if the access is successful. This is not set by the server, but is included in the http protocol. The string returned by final int httpCode = response.code (); ResponseBody responseBody = response.body (); / / can only be called once, with a return value on the first time and null on the second call. Final String res = responseBody.string (); / / returned binary byte array final byte [] bytes = responseBody.bytes (); / / returned InputStream final InputStream inputStream = responseBody.byteStream ();}})

> the non-blocking request is executed asynchronously. The execution result of the request is generally notified to the caller through API callback, which corresponds to the enqueue method in OKHTTP.

2.2 perform Post request 2.2.1 Post request key-value pair

   most of the time we need to transfer key-value pairs to the server through POST, and OkHttp provides a convenient way to do this. Making a Post request using OkHttp is similar to making a Get request, and it only takes five steps to complete:

Create an okHttpClient object

OkHttpClient client = new OkHttpClient ()

Build FormBody, pass in parameters

Okhttp3.FormBody.Builder builder = new FormBody.Builder (); builder.add ("username", "admin"); builder.add ("password", "admin"); FormBody formBody = builder.build ()

> the parameters of post are added by constructing a FormBody through key-value pairs. In fact, the post method needs to pass in a RequestBody object, which is used to carry the data to be submitted. FormBody is a subclass of RequestBody.

Build Request, passing in FormBody as a parameter of the Post method

Request request = new Request.Builder () .url (url) .post (formBody) .build ()

Encapsulate Request as Call

Call call = client.newCall (request)

Call synchronous or asynchronous request methods as needed.

/ / synchronous call returns Response, which corresponds to the execute method in OKHTTP and throws an IO exception. Response response = call.execute (); if (response.isSuccessful ()) {System.out.println (response.body (). String ());}

/ / execute a non-blocking request asynchronously. The execution result is usually communicated to the caller through API callback, which corresponds to the enqueue method in OKHTTP. Call.enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {} @ Override public void onResponse (Call call, final Response response) throws IOException {if (response.isSuccessful ()) {})

2.2.2 Post request to submit Json

Create an okHttpClient object

OkHttpClient client = new OkHttpClient ()

Build RequestBody, pass in parameters

MediaType mediaType = MediaType.parse ("application/json;charset=UTF-8"); RequestBody requestBody = RequestBody.create (mediaType, "{username:admin;password:admin}")

> the difference between this method and the previous approach is that when constructing a Request object, we need to construct an additional RequestBody object to carry the data we want to submit. When constructing the RequestBody, you need to specify the MediaType, which describes the content type of the request / response body.

Build Request, passing in FormBody as a parameter of the Post method

Request request = new Request.Builder () .url ("http://www.jianshu.com/").post(requestBody).build();

Encapsulate Request as Call

Call call = client.newCall (request)

Call synchronous or asynchronous request methods as needed.

/ / synchronous call, return Response, throw IO exception Response response = call.execute (); if (response.isSuccessful ()) {System.out.println (response.body (). String ());}

/ / the non-blocking request is executed asynchronously. The execution result is usually communicated to the caller through the API callback, which corresponds to the enqueue method in OKHTTP. Call.enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {} @ Override public void onResponse (Call call, final Response response) throws IOException {if (response.isSuccessful ()) {})

2.2.3 Post request to submit form

   We often encounter user registration on the web page, requiring you to enter a user name, password (and other parameters, of course, here is just an example), this is actually a form, so let's take a look at how to use OkHttp to submit the form. After learning above, you must understand that the main difference is that you can construct different RequestBody and pass them to the post method. Here we will use a MuiltipartBody, which is a subclass of RequestBody. We use this class to submit the form to build a RequestBody. In the following code, we will send a user's password to the server.

@ Testpublic void doPostForm () throws IOException {OkHttpClient okHttpClient = new OkHttpClient (); okhttp3.MultipartBody.Builder builder = new MultipartBody.Builder (); / / if you are submitting a form, be sure to set this builder.setType (MultipartBody.FORM); builder.addFormDataPart ("username", "admin"); builder.addFormDataPart ("password", "admin"); RequestBody requestBody = builder.build () Request request = new Request.Builder () .url ("https://en.wikipedia.org/w/index.php").post(requestBody).build(); Response response = okHttpClient.newCall (request). Execute (); if (! response.isSuccessful ()) {throw new IOException (" Unexpected code "+ response);} System.out.println (response.body (). String ()) 2.3.1 Post request to upload files

   next we'll introduce a Builder that can construct a RequestBody, called MultipartBuilder. When we need to do something similar to form upload, we can use it to construct our requestBody.

2.3.2 get requests to download the file @ Testpublic void doGetFilePro () {OkHttpClient okHttpClient = new OkHttpClient (); Request request = new Request.Builder () .url ("http://publicobject.com/helloworld.txt") .build (); Response response = okHttpClient.newCall (request). Execute (); if (! response.isSuccessful ()) {throw new IOException (" Unexpected code "+ response);} Headers headers = response.headers () For (int I = 0; I < headers.size (); iTunes +) {System.out.println (headers.name (I) + ":" + headers.value (I));} System.out.println (response.body (). String ());} 2.4 HTTP header attribute configuration

The typical HTTP header of    is like a Map, with one or no value for each field.

   when writing request headers, use header (name, value) to set unique name and value. If there is already a value, the old one will be removed and the new one will be added. Use addHeader (name, value) to add multiple values (add, do not remove existing ones).

   when reading the response header, use header (name) to return the last occurrence of name, value. Usually this is also the only name, value. If there is no value, then header (name) returns null. If you want to read all the values corresponding to the field, using headers (name) returns a list.

@ Testpublic void doHeader () throws IOException {OkHttpClient okHttpClient = new OkHttpClient (); Request request = new Request.Builder () .url ("https://api.github.com/repos/square/okhttp/issues"). Header (" User-Agent "," OkHttp Headers.java ") .addHeader (" Accept "," application/json ") Throw new IOException 0.5 ") .addHeader (" Accept "," application/vnd.github.v3+json ") .build (); Response response = okHttpClient.newCall (request). Execute (); if (! response.isSuccessful ()) {throw new IOException (" Unexpected code "+ response);} System.out.println (" Server: "+ response.header (" Server ")) System.out.println ("Date:" + response.header ("Date")); System.out.println ("Vary:" + response.headers ("Vary"));} III. Summary

   from the above example, we can find that OkHttp is very convenient to use in many cases, and a lot of code is duplicated, and the official OkHttp documentation does not recommend that we create multiple OkHttpClient, so we can use one globally.

Import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import okhttp3.*;import java.io.IOException;import java.util.Map;/** * take today's best performance as the latest starting point for tomorrow.

* Today the best performance as tomorrow newest starter! * * @ Class description: OkHttp basic use * @ author: single tear without trace * @ creation time: 2020-12-22 11:54 * @ version: v 1.0.1 * @ since: JDK 1.8 * @ official introduction * / @ Slf4jpublic final class OkHttpHelper {static ObjectMapper mapper = new ObjectMapper () / * get operation class * / private static final OkHttpClient okHttpClient = new OkHttpClient (); private static final String CHARSET_NAME = "UTF-8"; private static final MediaType JSONMediaType = MediaType.parse ("application/json;charset=UTF-8") / * * synchronous get request * * @ param url * @ return * @ throws IOException * / public static String doGet (String url) throws IOException {Request request = new Request.Builder () .get () .url (url) .build (); Call call = okHttpClient.newCall (request); return execute (request) } / * * Asynchronous get request * * @ param url * @ return * @ throws IOException * / public static void doSyncGet (String url) throws IOException {Request request = new Request.Builder () .get () .url (url) .build (); Call call = okHttpClient.newCall (request); enqueue (request) } / * synchronous post request * / public static String doPost (String url, Map params) throws IOException {RequestBody requestBody = RequestBody.create (JSONMediaType, mapper.writeValueAsString (params)); Request.Builder builder = new Request.Builder (); Request request = builder.url (url) .post (requestBody). Build (); log.info ("do post request and url [{}]", mapper.writeValueAsString (request)) Return execute (request);} / * * synchronous post request * / public static String doPost (String url, String params) throws IOException {RequestBody requestBody = RequestBody.create (JSONMediaType, params); Request.Builder builder = new Request.Builder (); Request request = builder.url (url) .post (requestBody). Build () Log.info ("do post request and url [{}]", mapper.writeValueAsString (request)); return execute (request);} / * * Asynchronous post request * / public static void doSyncPost (String url, String params) {RequestBody body = RequestBody.create (JSONMediaType, params); Request request = new Request.Builder (). Url (url) .post (body). Build (); enqueue (request) } public static String doPostJSON (String url, Map params, Headers headers) throws IOException {RequestBody requestBody = RequestBody.create (JSONMediaType, mapper.writeValueAsString (params)); Request.Builder builder = new Request.Builder (); Request request = builder.url (url) .post (requestBody) .headers (headers). Build (); log.info ("do post request and url [{}]", mapper.writeValueAsString (request)); return execute (request) Synchronous request will not start the asynchronous thread * * @ param request * @ return * @ throws IOException * / private static String execute (Request request) throws IOException {log.info ("request start: request address: {}", request.url ()); Response response = okHttpClient.newCall (request). Execute () If (response.isSuccessful ()) {String res = response.body () .string (); log.info ("request return: {}", res); return res;} else {throw new IOException ("Unexpected code" + response) }} / * * enable asynchronous thread access * * @ param request * @ param responseCallback * / public static void enqueue (Request request, Callback responseCallback) {okHttpClient.newCall (request) .enqueue (responseCallback) } / * enable asynchronous threads to access the network, and do not care about returning the result (implementing empty callback) * * @ param request * / private static void enqueue (Request request) {okHttpClient.newCall (request) .enqueue (new Callback () {@ Override public void onFailure (Call call, IOException e) {log.error ("", e)) } @ Override public void onResponse (Call call, Response response) throws IOException {Norway if (response.isSuccessful ()) {log.info ("Successful data acquisition. . . "); log.info (" response.code () = "+ response.code ()); log.info (" response.body () .string () = = "+ response.body () .string ());}) }} at this point, the study on "how to use the OkHttp Network request Framework" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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