Android development knowledge learning - HTTP basics

Learning resources come from: Throwing Object Line

HTTP

What exactly is HTTP?

  • Two intuitive impressions
    • Enter the browser address and open the web page.
    • Send a network request in Android and return the corresponding content
  • Hyper Text Transfer ProtocolHyper Text Transfer Protocol
    • Hypertext: Text displayed on a computer that contains links to other text - HTML

How HTTP works

发送请求
响应
浏览器
服务器

URL ->HTTP message

  • List item

How HTTP works

发送请求
响应
APP
服务器

Request message format: Request

Insert image description here

Response message format: Response

Insert image description here

HTTP request method

  • GET
    • Get resources, no body
GET /users/1 HTTP/1.1
Host: api.github.com

Code corresponding to Retrofit:

@GET{
    
    "/users/{id}"}
Call<User>getUser(@Path("id")String id)
  • POST
    • Add or modify resources and have a body
POST /users HTTP/1.1
Host: api.github.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

name=rengwuxian&gender=male

Code corresponding to Retrofit:

@FormUrlEncoded  //请求的编码方式为表单编码
@POST("/users")
Call<User> addUser(@Field("name") String name,
@Field("gender") String gender);
  • PUT
    • Modify resources and have a body
POST /users HTTP/1.1
Host: api.github.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
name=rengwuxian&gender=male

Code corresponding to Retrofit:

@FormUrlEncoded
@PUT("/users/{id}")
Call<User> updateGender(@Path("id") String id,
@Field("gender") String gender);
  • DELETE
    • Delete resources, no body
POST /users HTTP/1.1
Host: api.github.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
name=rengwuxian&gender=male

Code corresponding to Retrofit:

@DELETE("/users/{id}")
Call<User> getUser(@Path("id") String id,
@Query("gender") String gender);
  • HEAD
    • The usage method is exactly the same as GET
    • The only difference from GET is that there is no Body in the returned response

status code

  • Function: Provide a typed description of the results
    • 1xx: Temporary message. Such as: 100 (continue sending), 101 (switching protocol)
    • 2xx: Success. The most typical ones are 200 (OK) and 201 (created successfully).
    • 3xx: Redirect. Such as 301 (Permanently moved), 302 (Temporarily moved), 304 (Content unchanged).
    • 4xx: Client error. Such as 400 (client request error), 401 (authentication failed), 403 (forbidden), 404 (content not found).
    • 5xx: Server error. Such as 500 (server internal error)

Header

  • Role: Metadata of HTTP messages (metadata)

Host

target host address

Content-Type

Specify the type of Body. There are four main categories:

  1. text/html
    HTML text, used for browser page response

Requesting a web page returns the response type, and returns html text in the Body. The format is as follows:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 853
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
......
  1. x-www-form-urlencoded
    normal form.
    Submission method of plain text form on web page in encoded URL format .
    Insert image description here
    The format is as follows:
POST /users HTTP/1.1
Host: api.github.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 27

name=rengwuxian&gender=male

Code corresponding to Retrofit:

@FormUrlEncoded  //请求的编码方式为表单编码
@POST("/users")
Call<User> addUser(@Field("name") String name,
@Field("gender") String gender);
  1. The multipart/form-data
    multipart form is generally used to transmit multiple contents containing binary content.
    The submission method when the web page contains binary files.
    Insert image description here
    The format is as follows:
POST /users HTTP/1.1
Host: hencoder.com
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Length: 2382

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="name"

rengwuxian
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="avatar";
filename="avatar.jpg"
Content-Type: image/jpeg

JFIFHHvOwX9jximQrWa......
------WebKitFormBoundary7MA4YWxkTrZu0gW--

Code corresponding to Retrofit:

@Multipart
@POST("/users")
Call<User> addUser(@Part("name") RequestBody name,
@Part("avatar") RequestBody avatar);
...
RequestBody namePart =
RequestBody.create(MediaType.parse("text/plain"),
nameStr);
RequestBody avatarPart =
RequestBody.create(MediaType.parse("image/jpeg"),
avatarFile);
api.addUser(namePart, avatarPart);
  1. application/json, image/jpeg, application/zip...
    JSON format, used for Web Api responses or POST/PUT requests.
    Single content (text or non-text is acceptable), used for Web Api responses or POST/PUT requests.

Submit JSON in request

POST /users HTTP/1.1
Host: hencoder.com
Content-Type: application/json; charset=utf-8
Content-Length: 38

{
    
    "name":"rengwuxian","gender":"male"}

Code corresponding to Retrofit:

@POST("/users")
Call<User> addUser(@Body("user") User user);
...
// 需要使用 JSON 相关的 Converter
api.addUser(user);

Return JSON in response

HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
content-length: 234
[{
    
    "login":"mojombo","id":1,"node_id":"MDQ6VXNl
cjE=","avatar_url":"https://avatars0.githubuse
rcontent.com/u/1?v=4","gravat......

Submit binary content in request

POST /user/1/avatar HTTP/1.1
Host: hencoder.com
Content-Type: image/jpeg
Content-Length: 1575

JFIFHH9......

Code corresponding to Retrofit:

@POST("users/{id}/avatar")
Call<User> updateAvatar(@Path("id") String id, @Body
RequestBody avatar);
...
RequestBody avatarBody =
RequestBody.create(MediaType.parse("image/jpeg"),
avatarFile);
api.updateAvatar(id, avatarBody)

Return binary content in response

HTTP/1.1 200 OK
content-type: image/jpeg
content-length: 1575

JFIFHH9......
  1. image/jpeg/application/zip
    single file for Web Api response or POST/PUT request

Content-Length

Specify the length of the Body (bytes).

Transfer: chunked (ChunkedTransfer Encoding)

Used when the content length cannot be determined when the response is initiated. Not used together with Content-Length. The purpose is to respond as early as possible and reduce user waiting.
Format

HTTP/1.1 200 OK
Content-Type: text/html
Transfer-Encoding: chunked

4
Chun
9
ked Trans
12
fer Encoding
0

Location

Specify the target URL for redirection

User-Agent

The user agent (client) is who actually sends the request and receives the response, such as a mobile browser or a certain mobile app.

Range / Accept-Range

Specify the content range of the body.
Get data by range.
Accept-Range: bytesAppears in the response message, indicating that the server supports fetching range data by bytes.
Range: bytes=<start>-<end>Appears in the request message, indicating which piece of data
Content-Range:<start>-<end>/totalis to be fetched. Appears in the response message, indicating which piece of data is sent
.
Function: resume downloading from breakpoints, multi-threaded downloading.

Other Headers

  • Accept: The data types that the client can accept. Such as text/html
  • Accept-Charset: The character set accepted by the client. Such as utf-8
  • Accept-Encoding: The compression encoding type accepted by the client. Such as gzip
  • Content-Encoding: compression type. Such as gzip

Cache

Function: Cache data on the client or intermediate network nodes to reduce the frequency of fetching data from the server to improve network performance.

REST

There are different opinions on the definition of REST, and there is no unified answer.
A parabolic point of view: REST HTTP means using HTTP correctly. include:

  • Use the format of the resource to define the URL
  • Standardly use methods to define network request operations
  • Standardly use status code to indicate response status
  • Other design guidelines for compliance with the HTTP specification

After-school questions

  1. [Single-choice question] The user enters the address in the browser address bar and presses Enter. After a while, the browser displays the page. What happens behind this?
    A. The browser assembles the HTTP message and requests the server -> the server processes the request and returns the response message -> the browser processes the response message after receiving it and uses the rendering engine to render the interface
    B. The browser puts the URL in the address bar Send to the server -> The server sends the URL to the corresponding page image file back to the browser -> The browser displays the image after receiving it

Answer: A
Answer analysis: When the user enters the address in the address bar and presses Enter, the browser will find the corresponding server IP address through DNS resolution, and then establish a connection through the TCP/IP protocol. Once the connection is established, the browser will assemble the HTTP request message according to the URL in the address bar and send the request to the server. After receiving the request, the server will process it and return an HTTP response message. After the browser receives the response message, it will parse and process it, then use a rendering engine (such as HTML, CSS and JavaScript) to render the page interface, and finally display the page on the user's screen

  1. [Single-choice question] A URL such as http://api.qq.com/user/1, which parts can be broken into for the "HTTP assembly message"
    A. ① [http:]-> Protocol type ② 【//api.qq.com/user/1】-> Path
    B. ① 【http:】-> Protocol type ② 【//api.qq.com】-> Server address ③ 【/user/1】-> Path
    C. ① [http:]-> Protocol type ② [//api.qq.com/user/]-> Path ③ [1]-> File name

Answer: B
Answer analysis: In the HTTP assembly message, the URL can be split into the following parts:

  1. Protocol type: "http:" in the URL indicates the protocol type used, here it is HTTP.
  2. Server address: "//api.qq.com" in the URL indicates the target server address of the request.
  3. Path: "/user/1" in the URL indicates the requested path. It usually indicates the location of the requested resource or a specific status of the resource.
  4. File name: If the path contains a file name, such as "/user/1", then the file name is the last part of the path. But in the given URL, the file name is not included.
    So, according to this URL "http://api.qq.com/user/1", we can split it into the following parts:
    Protocol type: http:
    Server address: //api.qq.com
    Path: /user/1
    Therefore, the answer is B
  1. [Single-choice question] What are the parts of the HTTP request message?
    A. Request line, path, Headers, Body
    B. Request line, Headers, Body
    C. Request line, method, Host, Body

Answer: B
Answer analysis: HTTP request messages are usually divided into the following parts:

  1. Request Line: Contains the request method (such as GET, POST, etc.), the requested resource path and the HTTP protocol version.
  2. Headers: Contains various metadata related to the request, such as the context of the request, client information, server information, etc.
  3. Body: Contains the body content of the request, such as the data sent in a POST or PUT request. So the correct answer is B
  1. [Single-choice question] What three parts does the request line consist of?
    A. method, path, HTTP version
    B. method, path, Host
    C. method, server address, path

Answer: A
Answer analysis: The request line consists of three parts: the request method, the requested resource path, and the HTTP protocol version. So the answer is A

  1. [Single-choice question] What are the parts of the HTTP response message?
    A. Response header, response code, response information
    B. Status line, response header, Headers, Body
    C. Status line, Headers, Body

Answer: B
Answer analysis: HTTP response messages are usually divided into the following parts:

  1. Status Line: Contains the version of the HTTP protocol, the status code of the request, and the corresponding text description.
  2. Headers: Contains various metadata related to the response, such as the content type of the response, the context of the response, server information, etc.
  3. Body: Contains the body content of the response, that is, the data the browser should receive. So the correct answer is B
  1. [Single-choice question] What three parts does the status line of the response message consist of?
    A. HTTP version, API version, status code
    B. HTTP version, status code, status information
    C. HTTP version, Body type, status code

Answer: B
Answer analysis: The status line of the response message consists of three parts: HTTP version, status code and status information. Therefore, the answer is B

  1. [Multiple choice question] Which of the following are consistent with the GET method?
    A. Used to obtain resources
    B. Used to add or modify resources
    C. Only used to modify resources
    D. Used to delete resources
    E. Idempotent (that is, the same result will be obtained when called repeatedly)
    F. In the request message ContainsBody

Answer:
Answer analysis:

  1. [Multiple choice question] Which of the following are consistent with the POST method?
    A. Used to obtain resources
    B. Used to add or modify resources
    C. Only used to modify resources
    D. Used to delete resources
    E. Idempotent (that is, the same result will be obtained when called repeatedly)
    F. In the request message ContainsBody

Answer: A, E
Answer analysis: The GET method is used to obtain resources from the server, that is, to request specified data. It cannot be used to add, modify, or delete resources. The GET method is idempotent, meaning that you will get the same result when called multiple times. In addition, the GET method does not include Body in the request message. Therefore, the options that conform to the GET method are: A, E.

  1. [Multiple choice question] Which of the following are consistent with the PUT method?
    A. Used to obtain resources
    B. Used to add or modify resources
    C. Only used to modify resources
    D. Used to delete resources
    E. Idempotent (that is, the same result will be obtained when called repeatedly)
    F. In the request message ContainsBody

Answer: B, F
Answer analysis: The POST method is used to add or modify resources to the server. It can include Body in the request message to send data to the server. The POST method is not idempotent, meaning you may get different results when called multiple times. Therefore, the options that conform to the POST method are: B, F

  1. [Multiple choice question] Which of the following are consistent with the DELETE method?
    A. Used to obtain resources
    B. Used to add or modify resources
    C. Only used to modify resources
    D. Used to delete resources
    E. Idempotent (that is, the same result will be obtained when called repeatedly)
    F. In the request message ContainsBody

Answer: D, E
Answer analysis: The DELETE method is used to delete resources from the server. It is not used to obtain, add or modify resources. The DELETE method is idempotent, meaning that you will get the same result when called multiple times. In addition, the DELETE method does not include Body in the request message. Therefore, the options that comply with the DELETE method are: D, E.

  1. [Single choice question] What is the function of the Host header?
    A. Address the IP of the target host on the network, and confirm the host domain name and port after finding the target host
    B. Only used to address the IP of the target host
    C. Only used to confirm the host domain name and port after finding the target host

Answer: A
Answer analysis: Host is a request header field in the HTTP protocol, which is used to specify the host name and port number of the request. In network communication, the target host needs to be addressed through the IP address, and the function of the Host header field is to confirm the host domain name and port after finding the target host. Therefore, the answer is A

  1. [Single-choice question] When Content-Type is x-www-form-urlencoded, which of the following formats is the Body format in the request message?
    A. Encoded URL, that is, the form of name1=value1&name2=value2
    B. The form of transmitting each part of the content in multiple parts, using boundary to separate them
    C. JSON form, such as {"name1":value1,"name2":value2 }

Answer: A
Answer analysis: In the HTTP request, when the Content-Type is x-www-form-urlencoded, the Body in the request message takes the form of name1=value1&name2=value2, that is, the form of the encoded URL, with "&" Separate different parameters. Therefore, the answer is A

  1. [Single-choice question] When Content-Type is multipart/form-data, which of the following formats is the Body format in the request message?
    A. Encoded URL, that is, the form of name1=value1&name2=value2
    B. The form of transmitting each part of the content in multiple parts, using boundary to separate them
    C. JSON form, such as {"name1":value1,"name2":value2 }

Answer: B
Answer analysis: In an HTTP request, when the Content-Type is multipart/form-data, the Body in the request message uses the form of transmitting each part of the content in multiple parts, and uses boundary to separate them. Each part has its own Content-Type and Content-Disposition header fields that describe the content type and purpose of the part. Therefore, the answer is B

  1. [Single-choice question] When Content-Type is application/json, which of the following formats is the Body in the request message?
    A. Encoded URL, that is, the form of name1=value1&name2=value2
    B. The form of transmitting each part of the content in multiple parts, using boundary to separate them
    C. JSON form, such as {"name1":value1,"name2":value2 }

Answer: C
Answer analysis: When Content-Type is application/json, the Body in the request message adopts JSON format, that is, an object is wrapped in curly brackets {}. The object consists of multiple key-value pairs, and each key-value pair Use colons to separate them, and use commas to separate different key-value pairs. Therefore, the answer is C

  1. [Single-choice question] How does the HTTP code written by Android developers work?
    A. The Android system sends the URL written by the developer to the server. After processing, the server returns the data needed by the developer directly to the client, and then the developer's callback code processes the data.
    B. The Android code writes the developer The URL and other request information are assembled into an HTTP message, and an HTTP request is sent to the server in the form of a message. The server returns a standard HTTP message after processing the request. The client obtains the real data after processing the message, and then the developer's callback code output for processing

Answer: B
Answer analysis: The HTTP code written by Android developers mainly uses class libraries such as HttpURLConnection, HttpClient, and OkHttp to assemble the URL and other request information written by the developer into an HTTP message and send it to the server in the form of a message. HTTP request. The server returns a standard HTTP message after processing the request. After receiving the message, the client needs to parse and process it to obtain the real data. Finally, the developer's callback code processes the output. Therefore, option B is correct

Guess you like

Origin blog.csdn.net/weixin_74239923/article/details/134049805