HTTP in iOS you see, I'm good enough.

Source: Internet
Author: User
Tags connect socket http 2

HTTP is an old topic, we often need to send a post or GET request to the server in the project, but the understanding of HTTP should not be limited to this. A journey begins with a journey. The more you want to go far, the basic principle should be understood thoroughly comprehensive, just stay in the use of asihttprequest or afnetworking to send a parameter to the extent of the request is not enough. This article is to take you all aspects of the review of HTTP.

What you can gain from this article:

• The necessary elements for a complete HTTP request and response

· Differences between different versions of HTTP

· HTTP, Socket, TCP Differences (easy to mix)

First, the HTTP protocol

HTTP is essentially a protocol, the full name is Hypertext Transfer Protocol, the Hypertext Transfer Protocol. It can be seen from the name that the protocol is used to specify the transport rules between the client and the server, and that the transmitted content is not limited to text (in fact, any type of data can be transmitted).

Figure 1.1 Transport. png

Ii. content of HTTP requests and responses

What happened when we sent an HTTP request to the server?

Let's look at a sample POST request diagram:

Figure 2.1 Http_post request example. png

Note: This article uses paw to simulate sending HTTP requests, using Charles capture package, Charles selects "Request" and "Raw" option to see the full contents of the request

The above example diagram already contains a few essential elements of an HTTP request: A request line, a request header (Headerfield), a request body (body), and, similarly, a response with a status line, a response header, and an entity content. Next we unfold one by one.

1. Request Line

The request line contains the request method, the request Uniform Resource Identifier (URI), and the HTTP version number, as shown in the first line of 2.1:

Figure 2.2 Request line. png

    • The request method is the familiar post,, put, etc.

    • The URI is the URL to exclude the rest of the host, that is, the resource on the server local path

    • The HTTP version number, the current mainstream version is 1.1 (introduced in 1999), the latest version is 2.0 (released in May 2015). Differences between different versions will be expanded below

2. Request Header

The request header mainly holds the additional information that the client wants to give to the server, and the part of the box is the request header:

Figure 2.3 Request header. png

HTTP requests are represented in iOS with Nsurlrequest and nsmutablerequest, and HTTP responses are expressed in Nshttpurlresponse.

    • Host: Network address of the destination server

    • Accept: Let the server know the type of data that the client can receive, such as text/html */*

    • Data types in content-type:body, such as Application/json;

    • Accept-language: The locale of the client, such as ZH-CN

    • Accept-encoding: The data compression format supported by the client, such as Gzip

    • User-agent: The client's software environment, we can change the field for its own client name, such as QQ music v1.11, such as browser mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) applewebkit/600.8.9 (khtml, like Gecko) maxthon/4.5.2

    • Connection:keep-alive, this field starts with HTTP 1.1 and is used to tell the server that this is a persistent connection, "Please do not disconnect the TCP connection immediately after the response is made." More explanations of this field will be expanded in the following HTTP release brief.

    • The length of the content-length:body, if the body is empty, the field value is 0. This field is typically not available in post requests.

The body of the POST request may also be empty, so content-length in post may also be 0

    • Cookie: The user information of the logger is saved locally, and if any are automatically attached

It is worth mentioning that in iOS when you send an arbitrary request, whether you want to, Nsurlrequest will automatically help you to record the URL you visit the set of cookies. In iOS, it is a singleton, expressed in nshttpcookiestorage. by Nshttpcookiestorage *cookiejar = [Nshttpcookiestorage sharedhttpcookiestorage]; For (Nshttpcookie *cookie in [Cookiejar cookies]) {NSLog (@ "%@", cookie);} All cookies that are currently automatically saved can be obtained. If you are interested in the operation of cookies, please refer to the HTTP request using cookies in iOS for this article.

The above is our daily development of the more often encountered in the request header, in fact, there are other field, but the space limit can not be listed, want to know all the request header please see here Request header response Header list. How do I add these field settings in iOS? You can use the-[nsmutableurlrequest Addvalue:forhttpheaderfield:] method to get the field that the current request has been set to use-[nsurlrequest Allhttpheaderfields]. That is, we can use the above interface to customize the request header we need, but some field is not changed, we look at the description of iOS:

Figure 2.4 iOS Request Header interface description. png

From the documentation we can see that authorization Connection Host WW should not be on iOS

W-authenticate These header field to make changes.

3. The request body

The data that really needs to be sent to the server, the request body in the Post-multipart upload request is the binary NSData type data that uploads the file, the request body is empty in the GET request, and the request body in the normal POST request is some form data. In iOS, nsurlrequest and nsmutableurlrequest are generally used to represent the Httpbody attribute, adding body with-[nsmutableurlrequest sethttpbody:].

4. Response status Line

The status line is the status information returned by the server to the client, including the HTTP version number, status code, and the English name of the status code.

The following is a typical correct status line:

http/1.1 OK

This section needs to be about the error code. In fact, the HTTP request error code can be roughly divided into the following categories according to the error code from left to right first number:

1XX: Informational Tip. Does not represent a success or failure, indicating a temporary response, such as 100 for continuation, and 101 for switching protocol

2XX: Success

3XX: redirect

4XX: Client error, it is likely that the client has a problem, such as a kind of lovely 404 means that the file is not found, stating that your URI is problematic, the directory on the server is not the file; 414URI too long

5XX: Server error, such as 504 Gateway Timeout

Error code is not to remember, error and then check the corresponding error code meaning on the line. But knowing the classification above will help you make a general judgment at the first time, at least you can see why it is a server or a client.

5. Response Headers and Response entities

This part differs little from the request part, the Word field of the response header is slightly different, and the header field in the response header also goes to the Request header response header list.

Iii. Introduction to HTTP version

Here I have the HTTP version simple divided into three categories: 1.1 ago, 1.1, 2.0, for the three categories to make a major difference in the introduction:

Before HTTP 1.1

  • Persistent connections are not supported. Disconnect the TCP connection immediately once the server responds to the client

  • No request header and response header

  • The front and back requests of the client are synchronous. The next request must wait for the previous request to get a response from the server before it is issued, a bit like a multithreaded synchronization mechanism.

HTTP 1.1 (Mainstream version)

The following performance improvements were made compared to versions prior to 1.1

  • Add request header and response header

  • Supports persistent connections. The client specifies connection for keep-alive through the request header to inform the server not to release the connection immediately after the response is completed. HTTP is TCP-based and a TCP connection can handle multiple HTTP requests in HTTP 1.1

  • The client is asynchronous between different requests. The next request does not have to wait for the last request to come back, but to make a continuous request, a bit like multi-threaded asynchronous processing.

HTTP 2.0

In accordance with the principle of backward compatibility, the 1.1 version has the feature 2.0, also use the same API. However, 2.0 will be used only for HTTPS URLs. As 2.0 of the popularity of the need for a long time, not to expand here, more new features please refer to this article.

Http://www.uiseo.cn/http-status-codes

Let's focus on some of the changes made in the current 1.1 release. What are the benefits of supporting persistent connections? HTTP is TCP-based, and if the connection is frequently started and then disconnected, it will cost a lot of resources in the TCP three handshake and four waves, inefficient. To request a Web page for example, we know that an HTML page image resources are not directly embedded in the page, but simply provide a URL, the image still needs to send an additional HTTP request to download. A Web page often needs to go through an HTTP request from the request to the final load to the local. Requesting a Web page before version 1.1 requires multiple "handshake-wave" processes, each of which is independent of each other, while 1.1 and later versions require at least one time.

Again, the request is asynchronous, and its benefits refer to multithreaded asynchronous processing, which is not expanded here.

The above features can be shown in Figure 2.3:

Figure 3.1 asynchronous request. jpg

We can see that: 1, n requests in fact only established 1 TCP connections, 2, n times the request is issued continuously asynchronously.

Iv. the difference between HTTP, Socket, and TCP

These three concepts are often talked about and are relatively easy to get mixed up with. Before we go back, let's look at the location of these three in the TCP/IP protocol family:

Figure 4.1 Hierarchical relationships. png

HTTP is the protocol of the application layer, which is closer to the client, TCP is the protocol of the Transport layer, and the socket is an abstraction layer from the transport layer, which is essentially an interface. So essentially three species are still very well differentiated. However, sometimes you may be confused, what is the difference between an HTTP connection, a TCP connection, and a socket connection? Well, if the figure above is not clear enough, we continue to look down.

1, the difference between TCP connection and HTTP connection

As mentioned above, HTTP is TCP-based, the first step for the client to send an HTTP request to the server is to establish a TCP connection to the server, that is, the first three handshake, "Hello, hello, hello." Supports persistent connections starting with HTTP 1.1, which means that a TCP connection can send multiple HTTP requests at a time.

Small summary: HTTP based on TCP

2, the difference between the TCP connection and the socket connection

In Figure 4.1, we mentioned that the socket layer is just an abstraction interface layer made on the TCP/UDP transport layer, so a socket connection can be based on TCP, or it may be based on UDP. The TCP protocol-based socket connection also needs to be connected through three handshake, is reliable, UDP protocol-based socket connection does not need to establish a connection process, but the other side can not receive will send the past, is unreliable, most of IM is the latter.

Small summary: Sockets can also be based on TCP

3, the difference between the HTTP connection and the socket connection

The distinction between the two concepts is more meaningful, after all, TCP can not see the touch, HTTP and socket is actually useful.

    • HTTP is a short connection, and the Socket (based on TCP protocol) is a long connection. Although HTTP1.1 begins to support persistent connections, it is still not guaranteed to always connect. In the case of a socket connection, the connection state is maintained once the TCP three handshake is established, unless one is actively disconnected.

    • The HTTP connection server cannot initiate a message, and the socket connection request is limited by the sending sequence. This is important because it will determine the appropriate scenario for each of the two. HTTP uses a "request-response" mechanism, and the server cannot push messages to the client until the client has sent a message to the server. The client must be satisfied to send a message before the server replies back. Socket connection similar to the peer2peer relationship, one party may at any time shout to the other party.

4, the question came: when to use HTTP, when to use the socket

It is natural that the question be raised. When you receive a network communication with the other side of the demand, will naturally consider using HTTP or socket.

    • In the case of http: The two sides do not need to stay connected online, such as the acquisition of client resources, file upload, etc.

    • With sockets: Most instant Messaging Applications (QQ,), chat rooms, Apple APNs, etc.

In iOS, HTTP requests are typically made with native nsurlconnection, nsurlsession, or open source afnetworking (recommended), ASIHTTPRequest (stopped updating). Connect socket connection I used more than the Robbiehanson Cocoaasyncsocket (Xmppframework is also from his hand).

V. the end

The above is a review of the concept of HTTP, suitable for beginners are also suitable for experienced students to review together.

Welcome to leave a message, if you write the wrong place also please be generous to point out.

HTTP in iOS you see, I'm good enough.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.