HTTP is an object-oriented protocol belonging to the application layer, which is suitable for distributed hypermedia information System because of its simple and fast way. It was proposed in 1990, after several years of use and development, has been continuously improved and expanded. Currently used in the WWW is the sixth edition of Http/1.0, http/1.1 is in progress, and Http-ng (Next Generation of HTTP) has been proposed.
The main features of the HTTP protocol can be summarized as follows:
1. Support client/server mode.
2. Simple and quick: When a client requests a service from a server, it simply transmits the request method and path. The request method commonly has, POST. Each method prescribes a different type of customer contact with the server. Because the HTTP protocol is simple, the HTTP server's program is small, so the communication speed is very fast.
3. Flexible: HTTP allows the transfer of any type of data object. The type being transferred is marked by Content-type.
4. No connection: The implication of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives a reply from the customer, the connection is disconnected. In this way, the transmission time can be saved.
5. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory capability for transaction processing. A lack of status means that if the preceding information is required for subsequent processing, it must be retransmission, which may result in an increase in the amount of data transmitted per connection. On the other hand, it responds faster when the server does not need prior information.
First, HTTP
1.1 http protocol detailed URL of the article
HTTP (Hypertext Transfer Protocol) is based on the request and response mode, stateless, Application layer protocol, often based on TCP connection, HTTP1.1 version of a continuous connection mechanism, the vast majority of web development, are built on the HTTP protocol on the Web applications.
The format of the HTTP URL, which is a special type of URI that contains enough information to find a resource, is as follows:
http://host[":" Port][abs_path]
HTTP indicates that a network resource is to be located through the HTTP protocol; Host represents a legitimate Internet host domain name or IP address; port specifies a port number, NULL, and the default port 80;abs_path specifies the URI of the requested resource; If Abs_ is not given in the URL Path, then when it is the request URI, it must be given in the form of "/", which is usually done automatically by the working browser.
eg
1, Input: www.guet.edu.cn browser automatically converted into: http://www.guet.edu.cn/
2, http:192.168.0.116:8080/index.jsp
1.2 HTTP protocol Detailed request
The HTTP request consists of three parts: the request line, the message header, the request body
1. The request line begins with a method symbol, separated by a space, followed by the requested URI and protocol version, in the following format:
Method Request-uri Http-version CRLF
Where method represents the request methods; Request-uri is a Uniform Resource identifier, http-version represents the HTTP protocol version of the request, and CRLF represents a carriage return and a newline (except for the CRLF at the end, a separate CR or LF character is not allowed).
The request method (all uppercase) has a variety of methods, which are interpreted as follows:
Get request gets the resource identified by Request-uri
Post appends new data to the resource identified by Request-uri
The head request gets the response message header of the resource identified by Request-uri
The put request server stores a resource and uses Request-uri as its identity
Delete requests that the server delete the resources identified by the Request-uri
TRACE requests that the server echo the requested information received, primarily for testing or diagnostics
CONNECT reserved for future use
Options request query server performance, or query resource-related choices and requirements
Application Examples:
Get method: When accessing a Web page in the browser's address bar, the browser takes the access method to the server to obtain resources, eg:get/form.html http/1.1 (CRLF)
The Post method requires the requested server to accept the data appended to the request and is often used to submit the form.
eg:post/reg.jsphttp/(CRLF)
Accept:image/gif,image/x-xbit,... (CRLF)
...
HOST:www.guet.edu.cn (CRLF)
Content-length:22 (CRLF)
Connection:keep-alive (CRLF)
Cache-control:no-cache (CRLF)
(CRLF)//The CRLF indicates that the message header has ended before the message header
user=jeffrey&pwd=1234//This is the data submitted below
The head method is almost the same as the Get method, and the HTTP header contains information that is the same as the information that is received from the request. Using this method, you can get information about the resources identified by Request-uri without having to transfer the entire resource content. This method is often used to test the validity of a hyperlink, whether it can be accessed, and whether it has recently been updated.
2, the request header later described
3, the request body (slightly)
1.3 HTTP protocol in the answer to the detailed text
After receiving and interpreting the request message, the server returns an HTTP response message.
The HTTP response is also composed of three parts: status line, message header, response body
1, the status line format is as follows:
Http-version Status-code reason-phrase CRLF
Where http-version represents the version of the server HTTP protocol, Status-code represents the response status code sent back by the server, and reason-phrase a textual description of the status code.
The status code consists of three digits, the first number defines the category of the response, and there are five possible values:
1XX: Indicates information--indicates that the request has been received and continues processing
2XX: Success-Indicates that the request has been successfully received, understood, accepted
3XX: Redirect-requires further action to complete the request
4XX: Client Error--Request has a syntax error or the request cannot be implemented
5XX: Server-side Error-Server failed to implement legitimate request
Common status Code, status description, Description:
OK//Client Request successful
Bad Request//client requests have syntax errors that cannot be understood by the server
401 Unauthorized//request unauthorized, this status code must be used in conjunction with the Www-authenticate header field
403 Forbidden//server receives request, but refuses to provide service
404 Not Found//request resource does not exist, eg: entered the wrong URL
Internal Server error//Servers unexpected error
503 Server unavailable//servers are currently unable to process client requests and may return to normal after a period of time
eg:http/1.1 OK (CRLF)
2, the response header later described
3, the response body is the content of the resources returned by the server
1.4 HTTP protocol Detailed message header
HTTP messages consist of requests from the client to the server and responses from the server to the client. Both the request message and the response message are from the start line (for the request message, the start line is the request line, for the response message, the start line is the status line), the message header (optional), the empty line (only the CRLF row), and the message body (optional).
The HTTP message header includes a normal header, a request header, a response header, and an entity header.
Each header field is made up of the name + ":" + space + value, and the name of the message header field is case independent.
1. General Header
In the normal header, a few header fields are used for all requests and response messages, but not for the transmitted entities, only for the transmitted messages.
eg
Cache-control is used to specify a caching instruction, the cache instruction is one-way (the cached instruction appearing in the response may not appear in the request), and is independent (a message's caching instruction does not affect the caching mechanism of another message processing), and HTTP1.0 uses a similar header domain as pragma.
The cached instruction at request includes: No-cache (used to indicate that the request or response message cannot be cached), No-store, Max-age, Max-stale, Min-fresh, only-if-cached;
The caching instructions for the response include: public, Private, No-cache, No-store, No-transform, Must-revalidate, Proxy-revalidate, Max-age, S-maxage.
Eg: in order to instruct IE browser (client) do not cache pages, server-side JSP program can be written as follows: Response.sehheader ("Cache-control", "No-cache");
Response.setheader ("Pragma", "no-cache"); function equivalent to the above code, usually both//shared
This code sets the normal header field in the Sent response message: Cache-control:no-cache
The date normal header field represents the day and time the message was generated
Connection the normal header field allows you to send the option to specify a connection. For example, specify that the connection is contiguous, or specify the "close" option to notify the server that when the response completes, the connection is closed
2. Request Header
The request header allows the client to deliver the requested additional information to the server side as well as the client's own information.
Common Request Headers
The Accept Request header field is used to specify which types of information the client accepts. Eg:accept:image/gif, indicating that the client wants to accept a resource in GIF format; accept:text/html, which indicates that the client wants to accept HTML text.
The Accept-charset request header field is used to specify the character set accepted by the client. eg:accept-charset:iso-8859-1,gb2312. If you do not set this field in the request message, the default is that any character set is acceptable. 、
The Accept-encoding request header field is similar to the Accept, but it is used to specify an acceptable content encoding. Eg:accept-encoding:gzip.deflate. If the domain server is not set in the request message, the client is assumed to be acceptable for various content encodings.
The Accept-language request header field is similar to Accept, but it is used to specify a natural language. EG:ACCEPT-LANGUAGE:ZH-CN. If the header domain is not set in the request message, the server assumes that the client is acceptable to all languages.
The authorization request header domain is primarily used to prove that the client has permission to view a resource. When a browser accesses a page, if the response code received from the server is 401 (not authorized), you can send a request containing the authorization request header domain to require the server to authenticate it.
The host request header domain is primarily used to specify the Internet host and port number of the requested resource, which is usually extracted from the HTTP URL, which is required when sending the request, eg: we enter in the browser: http://www.guet.edu.cn/index.html
In the request message sent by the browser, the Host request header domain is included, as follows: Host:www.guet.edu.cn
The default port number 80 is used here, and if the port number is specified, it becomes: Host:www.guet.edu.cn: Specify the port number
User-agent when we go online to the forum, we often see some welcome information, which lists the name and version of your operating system, the name and version of the browser you are using, which often makes a lot of people feel amazing, actually, The server application obtains this information from the User-agent request header domain. The User-agent request header domain allows the client to tell the server about its operating system, browser, and other properties. However, this header domain is not required, if we write a browser ourselves, do not use the User-agent request header domain, then the server side can not know our information.
Request Header Example:
Get/form.html http/1.1 (CRLF)
Accept:image/gif,image/x-xbitmap,image/jpeg,application/x-shockwave-flash,application/vnd.ms-excel,application /vnd.ms-powerpoint,application/msword,*/* (CRLF)
ACCEPT-LANGUAGE:ZH-CN (CRLF)
Accept-encoding:gzip,deflate (CRLF)
IF-MODIFIED-SINCE:WED,05 2007 11:21:25GMT (CRLF)
if-none-match:w/"80b1a4c018f3c41:8317" (CRLF)
user-agent:mozilla/4.0 (compatible; MSIE6.0; WindowsNT 5.0) (CRLF)
Host:www.guet.edu.cn (CRLF)
Connection:keep-alive (CRLF)
(CRLF)
3, Response header
The response header allows the server to pass additional response information that cannot be placed in the status row, as well as information about the server and the next access to resources identified by Request-uri.
Frequently used response headers
The Location response header field is used to redirect the recipient to a new location. The location response header domain is often used when changing a domain name.
The server Response header field contains the software information that the servers use to process the request. Corresponds to the user-agent request header domain. The following is an example of the Server response header domain: server:apache-coyote/1.1
The www-authenticate response header domain must be contained in a 401 (unauthorized) response message when the client receives a 401 response message and sends the authorization header domain to request the server to authenticate it, and the service-side response header contains the header field.
eg:www-authenticate:basicrealm= "Basic Auth test!" You can see that the server is using the Basic authentication mechanism for the requested resource.
4, Entity header
Both request and response messages can transmit an entity. An entity consists of an Entity header field and an entity body, but does not mean that the entity header field and the entity body are sent together, and that only the Entity header field can be sent. The entity header defines meta information about the entity body (eg: there is no entity body) and the resource identified by the request.
Common entity Headers
The Content-encoding Entity header field is used as a modifier of the media type, and its value indicates the encoding of the additional content that has been applied to the entity body, and therefore the corresponding decoding mechanism must be used to obtain the media type referenced in the Content-type header domain. Content-encoding the compression method used to record documents, Eg:content-encoding:gzip
The Content-language Entity header field describes the natural language used by the resource. If the domain is not set, the entity content will be provided to all languages for reading
Actors Eg:content-language:da
The Content-length Entity header field is used to indicate the length of the entity body and decimal digits stored in bytes.
The Content-type entity header domain Term indicates the media type of the entity body that is sent to the recipient. eg
Content-type:text/html;charset=iso-8859-1
content-type:text/html;charset=gb2312
The Last-modified Entity header field is used to indicate the date and time the resource was last modified.
Expires the Entity header field gives the date and time the response expired. In order for the proxy server or browser to update the cache after a period of time (accessing the visited pages directly from the cache, shortening the response time and reducing the server load), we can use the Expires Entity header field to specify when the page expires. eg:expires:thu,15 Sep2006 16:23:12 GMT
HTTP1.1 clients and caches must consider other illegal date formats (including 0) as expired. Eg: in order for the browser to not cache the page, we can also use the Expires entity header domain, set to 0,jsp in the following: Response.setdateheader ("Expires", "0");
Author: Jeffrey from: http://blog.csdn.net/gueter/article/details/1524447
Tool class for Httputil.java
public class Httputil {public static string HttpGet (String httpurl) {string result = ' ";
Defaulthttpclient httpclient = new Defaulthttpclient ();//Create HTTP client httpget HttpGet = new HttpGet (Httpurl);
HttpResponse response = null; Httpparams params = Httpclient.getparams ();
Compute the network timeout with httpconnectionparams.setconnectiontimeout (params, 15 * 1000);
Httpconnectionparams.setsotimeout (Params, 20 * 1000);
try {response = Httpclient.execute (HttpGet);
httpentity entity = response.getentity ()//Get HTTP Content response.getstatusline (). Getstatuscode ()//Get HTTP status return value result = Entityutils.tostring (response.getentity ());//Get a specific return value, typically an XML file Entity.consumecontent (); If entity is not empty, the memory space is freed Httpclient.getcookiestore ();//Get Cookis Httpclient.getconnectionmanager (). Shutdo
WN ()//close HTTP client} catch (Clientprotocolexception e) {e.printstacktrace (); catch (IOException e) {e.printstacktrace ();
return result;
public static string HttpPost (string httpurl, String data) {string result = ' ";
Defaulthttpclient httpclient = new Defaulthttpclient ();
HttpPost HttpPost = new HttpPost (Httpurl);
Httpclient.setcookiestore (Datadefine.mcookiestore); Httpparams params = Httpclient.getparams ();
Compute the network timeout with httpconnectionparams.setconnectiontimeout (params, 15 * 1000);
Httpconnectionparams.setsotimeout (Params, 20 * 1000);
Httppost.setheader ("Content-type", "Text/xml");
Stringentity httppostentity;
try {httppostentity = new stringentity (data, "UTF-8");
Httppost.setentity (httppostentity);
HttpResponse response = Httpclient.execute (HttpPost);
httpentity entity = response.getentity ()//Get HTTP Content response.getstatusline (). Getstatuscode ()//Get HTTP status return value REsult = entityutils.tostring (Response.getentity ());//Get concrete return value, typically XML file Entity.consumecontent ();//If entity is not empty, Then free the memory Space Httpclient.getcookiestore ()//Get Cookis Httpclient.getconnectionmanager (). Shutdown ()//Turn off HT
TP client} catch (Exception e) {e.printstacktrace ();
}//Base64 is an encoded string that can be understood as a string//stringentity httppostentity = new Stringentity ("UTF-8");
return result; }
}
Second, HTTPS
HTTPS (Hypertexttransfer Protocol over Secure Socket Layer, SSL based HTTP protocol) uses the HTTP protocol, but HTTPS uses a different default port than the HTTP protocol and a cryptographic, Authentication layer (between HTTP and TCP). The initial development of the Protocol, which was conducted by Netscape, provides authentication and encryption communications, and is now widely used for security-sensitive communications on the Internet.
The client has the following steps when communicating with a Web server using HTTPS, as shown in the figure.
(1) Customers use the HTTPS URL to access the Web server and require an SSL connection with the Web server.
(2) When a Web server receives a client request, it transmits a copy of the site's certificate information (the certificate contains the public key) to the client.
(3) The client's browser and the Web server begin to negotiate the security level of the SSL connection, which is the level of information encryption.
(4) The client's browser establishes the session key according to the agreed security level, then encrypts the session key using the public key of the website and transmits it to the website.
(5) The Web server decrypts the session key using its own private key.
(6) The Web server uses the session key to encrypt communication with the client.
Tool class for Httpsutil.java
public class Httpsutil {static trustmanager[] Xtmarray = new mytmarray[] {new Mytmarray ()};//Create trust rule list Private fi
nal static int connent_timeout = 15000;
Private final static int read_timeout = 15000; static Hostnameverifier do_not_verify = new Hostnameverifier () {public boolean VERIFY (String hostname, sslsession
Session} {return true;
}
}; /** * Trust all hosts-do not check for any certificates create a trusts manager that does not validate * certificate chains, Android uses X509 certificate information mechanism, Install the all-trusting Trust * Manager * * private static void Trustallhosts () {try {Sslco
ntext sc = sslcontext.getinstance ("TLS");
Sc.init (NULL, Xtmarray, New Java.security.SecureRandom ());
Httpsurlconnection. Setdefaultsslsocketfactory (Sc.getsocketfactory ());
does not carry on the host name confirmation, to all host Httpsurlconnection.setdefaulthostnameverifier (do_not_verify); catch (Exception e) {E.printStackTrace (); }///**//* HTTPS get method, return value is HTTPS request, server-side returned data String type, data for XML parsing//*//public static String HTTPS
Get (String Httpsurl) {//Return httpspost (Httpsurl, NULL); /** * HTTPS Post method, the return value is HTTPS request, server-side returned data String type, data XML parsing */public static String Httpspost (St
Ring Httpsurl, String data} {string result = NULL;
HttpURLConnection http = null;
URL url;
try {url = new URL (httpsurl);
Whether it is an HTTP request or an HTTPS request if (Url.getprotocol (). toLowerCase (). Equals ("https")) {trustallhosts ();
http = (httpsurlconnection) url.openconnection (); ((httpsurlconnection) HTTP). Sethostnameverifier (do_not_verify);//No host name confirmation} else {http = (http
URLConnection) url.openconnection ();
} http.setconnecttimeout (Connent_timeout);/Set timeout time http.setreadtimeout (read_timeout); If(data = null)
{Http.setrequestmethod ("get");//Set Request type Http.setdoinput (true);
Http.setrequestproperty ("Content-type", "Text/xml");
if (Appsession.mcookiestore!=null) http.setrequestproperty ("Cookie", Appsession.mcookiestore);
else {Http.setrequestmethod ("post");//Set the request type to POST http.setdoinput (true);
Http.setdooutput (TRUE);
Http.setrequestproperty ("Content-type", "Text/xml");
if (Appsession.mcookiestore!=null &&appsession.mcookiestore.trim (). Length () > 0)
Http.setrequestproperty ("Cookie", Appsession.mcookiestore);
DataOutputStream out = Newdataoutputstream (Http.getoutputstream ());
Out.writebytes (data);
Out.flush ();
Out.close (); }//Set HTTP return status 2(OK) or 403 Appsession.httpsresponsecode = Http.getresponsecode ();
BufferedReader in = null;
if (Appsession.httpsresponsecode = =) {GetCookie (HTTP);
in = new BufferedReader (Newinputstreamreader (Http.getinputstream ()));
else in = new BufferedReader (Newinputstreamreader (Http.geterrorstream ()));
String temp = In.readline ();
while (temp!= null) {if (result!= null) result = temp;
else result = temp;
temp = In.readline ();
} in.close ();
Http.disconnect ();
catch (Exception e) {e.printstacktrace ();
return result; /** * Get cookie */private static void GetCookie (HttpURLConnection http) {String cookieval
= NULL;
String key = null; Appsession.mcookiestore = ""; for (int i = 1; (Key = Http.getheaderfieldkey (i))!= null;
i++) {if (Key.equalsignorecase ("Set-cookie")) {Cookieval =http.getheaderfield (i);
Cookieval =cookieval.substring (0, Cookieval.indexof (";"));
Appsession.mcookiestore =appsession.mcookiestore + cookieval + ";"; }
}
}
}
Third, WebService
In the "WEB Service development Detailed information" material introduced in detail webservice, so this article only posted Android code.
/** *webservice Call return value */public static string Invoke (Stringnamespace, String methodname, String Httpurl, Map<str ING, object> map) {try {//Instantiate Soapobject,invokerws Call WebService method name for server soapobject request = new Soap
Object (NameSpace, MethodName);
Sets the parameter of the calling method, which is the requested if (map!= null) {set<string> keyset = Map.keyset () of the server end, or returns a collection of keys
Iterator<string> it = Keyset.iterator ();
while (It.hasnext ()) {//The first iteration method takes the key value Object key = It.next ();
Request.addproperty (Key.tostring (), Map.get (key). ToString ());
LOG.I (Key.tostring (), Map.get (key). ToString ());
The element username = new Element (). createelement (NameSpace, "username");
Username.addchild (Node.text, "mobile");
Element pass = new Element (). createelement (NameSpace, "Password");
Pass.addchild (Node.text, "111111");
Element[] Header = new element[1]; Header[0] = new Element (). createelement (NameSpace, "Credentialsoapheader");
Header[0].addchild (node.element, username);
Header[0].addchild (node.element, pass); Sets the SOAP request information, obtains the serialized envelope soapserializationenvelope envelope = new Soapserializationenvelope (so
APENVELOPE.VER11);
Envelope.headerout = header;
Envelope.bodyout = Request;
Envelope.dotnet = true;
Envelope.setoutputsoapobject (Request);
Constructs the transport object, indicating that the URL Httptransportse httpTransport = new Httptransportse (Httpurl, 10000);
Httptransport.debug = true;
Call Webservice,methodname is the method name Httptransport.call (NameSpace + methodname, envelope) that invokes the server;
Get the return result of the server returns Envelope.getresponse (). toString ();
}catch (Exception e) {log.e ("Webservieinvoker.invoke", E.getmessage ());
return null; }