“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

This article through okhttp to obtain Baidu Encyclopedia OKHTTP introduction information, that is, this piece of information

There are four main steps: 1. Find the corresponding link request through the console. 3. Make a request to get the returned object and get the HTML page in the returned object. 4

Get link request

Open the OkHTTP Baidu Encyclopedia in your browser and find the link information that returns the information

Use Maven to import the OKHTTP and the JAR packages needed to parse the page

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.6.0</version>
</dependency>

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.8.3</version>
</dependency>
Copy the code

Build request

OkHttpClient client = new OkHttpClient(); / / request corresponding baidu encyclopedia address URL urlStr = new URL (” https://baike.baidu.com/item/okhttp/20447138?fr=aladdin “); Request = new request.builder () // Request interface. If you need to pass the parameter to join the interface. .url(urlStr) // Request type.get().build();

Make a request to get the returned object and get the HTML page in the returned object

Response Response = null; Response = client.newCall(request).execute(); Jsong = response.body().string();

Get the request to parse the HTML page and get the required values

Parse (jsong); Document Document = Jsoup. Parse (jsong); / / to get the corresponding class the following Elements divLemmaSummary = document. GetElementsByClass (” lemma – summary “); Elements div = divlemMasumMary. select(“div”); System.out.println(div.get(0).text()));

Last thing to get:

Android Web framework OKhttp, an open source project for handling web requests, is the most popular lightweight framework for Android, contributed by Mobile payments company Square (which also contributed Picasso) [1] to replace HttpUrlConnection and Apache HttpClient(Android API23 6.0 has removed HttpClient, now is not available)

The final Elements div object has four pieces of data, subscript 0 as shown above, and the other three as shown on the page, each line being a single piece of data. The functionality of the code is written in the code comment.

Import jar package successfully, copy code in order to use