Learning goals
- To know the HTTP
- The use of OKHttp
- Network data parsing
HTTP
Wikipedia: en.wikipedia.org/wiki/Hypert…
HTTP is short for Hyper Text Transfer Protocol. It is used to Transfer hypertext from the World Wide Web server to the local browser. Here said hypertext, is to use the method of hyperlink, will be different space text information organized together mesh text, can be understood as a web page. So HTTP is essentially a set of rules that servers and terminals follow to transfer and parse data. So what’s the rule? This rule mainly defines the data structure of HTTP requests and HTTP responses.
The HTTP request
An HTTP request message to the server consists of the following formats: request line, header, blank line, and request data. The request data part can be absent, but the rest must be, for example:
-- Request line, including request method (GET), URL (/), protocol version (HTTP/1.1) GET/HTTP/1.1 -- request header Host: www.example.com user-agent: Mozilla / 5.0 Accept: text/HTML and application/XHTML + XML, application/XML. Q = 0.9, image/avif, image/webp, * / *; Q = 0.8 Accept - Language: en - GB, en. Q =0.5 Accept-encoding: gzip, deflate, BR Connection: keep-alive -- blank lineCopy the code
The HTTP response
The HTTP response also consists of four parts: the status line, the message header, the blank line, and the response body.
Date: Mon, 23 May 2005 22:38:34 GMT Content-Type: text/ HTML; charset=UTF-8 Content-Length: 155 Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Server: Apache/1.3.3.7 (Unix) (Red-hat /Linux) ETag: "3f80F - 1B6-3e1CB03b" Accept-Ranges: bytes Connection: < HTML > <head> <title>An Example Page</title> </head> <body> <p>Hello World, this is a very simple HTML document.</p> </body> </html>Copy the code
In addition, HTTP protocol is not necessarily the transfer of web pages, there are other data structures. For example, in the browser input URL:api.github.com/users/uncle… The result is key-value pair data, which we call JSON data:
{
"login": "uncleleonfan",
"id": 8477402,
"node_id": "MDQ6VXNlcjg0Nzc0MDI=",
"avatar_url": "https://avatars.githubusercontent.com/u/8477402?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/uncleleonfan",
"html_url": "https://github.com/uncleleonfan",
"followers_url": "https://api.github.com/users/uncleleonfan/followers",
"following_url": "https://api.github.com/users/uncleleonfan/following{/other_user}",
"gists_url": "https://api.github.com/users/uncleleonfan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/uncleleonfan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/uncleleonfan/subscriptions",
"organizations_url": "https://api.github.com/users/uncleleonfan/orgs",
"repos_url": "https://api.github.com/users/uncleleonfan/repos",
"events_url": "https://api.github.com/users/uncleleonfan/events{/privacy}",
"received_events_url": "https://api.github.com/users/uncleleonfan/received_events",
"type": "User",
"site_admin": false,
"name": "Leon Fan",
"company": null,
"blog": "",
"location": null,
"email": null,
"hireable": null,
"bio": null,
"twitter_username": null,
"public_repos": 104,
"public_gists": 0,
"followers": 298,
"following": 2,
"created_at": "2014-08-18T08:14:59Z",
"updated_at": "2021-12-19T07:16:30Z"
}
Copy the code
OKHttp
Making: github.com/square/okht…
OKhttp is an open source web library that encapsulates Http request and response methods, making it easy to send Http requests and get Http responses in Android applications.
Usage:
If an Android application wants to use the web, you need to declare network permissions in androidmanifest.xml.
If you do not declare network permission, a permission exception will be thrown during the subsequent call to the network:
E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.xuneng.helloworld, PID: 28405
java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:150)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getAllByName(InetAddress.java:1152)
at okhttp3.Dns$Companion$DnsSystem.lookup(Dns.kt:49)
Copy the code
Add the Okhttp dependency
Go to build.gradle in the project app module, add the Okttp dependency, and click the Sync Now button to download the OKhttp library.
3. Send the request
Create a method in mainActivity.java that sends the request to sendRequest().Note that in Android, network requests are time-consuming IO operations that need to be placed in child threads. The main thread (UI thread) only does UI operations. With the enqueue method, network requests are executed in child threads. Once the sendRequest method is complete, it can be called in the onCreate method of the MainActivity to initiate a network request.
Run the code and, if the request is successful, execute the callback method onResponse to print a log:
Before running the code to the emulator, you can check whether the emulator can be accessed properly by sending the URL github.com/square/okht… Copy and paste it into the emulator’s browser to see if it returns data normally. If the simulator cannot return normally, you can search how to solve the network problem of the simulator, or directly connect the computer to the Android phone, open the USB debugging mode, and run the code on the real computer.
Network data parsing
OKhttp network request returns a Response object. How to parse the Response object and get the data we want? We request api.github.com/users/uncle mentioned above… The return is a JSON data format, so we’ll use JSONObject for parsing.
Log after code execution: