HTTP Communication in Android

Source: Internet
Author: User


Foreword: Recently in the MU class network to learn the course of the Internet courses in Android HTTP communication, I summed up a bit, which reference a lot of blog, thank you for sharing.

The article includes the following:
1.HTTP Introduction
The difference between 2.http/1.0 and http/1.1
3.HTTP request header, response header and status code
HttpURLConnection in 4.Android

1.Http Introduction
Http (Hypertext Transfer Protocol) defines how a browser can send a world Wide Web document to a World Wide Web server and how the server sends the document to the server. At a hierarchical level, HTTP is an application-level protocol, which is the basis for the World Wide Web to reliably exchange documents.
Workflow for HTTP
When the user clicks on a link (assuming the URL is http://www.tsinghua.edu.cn/chn/yxsz/index.html), the event flow occurs:
(1) The URL of the page to which the browser parses the connection.
(2) The browser resolves the IP address of the www.tsinghua.edu.cn to the DNS request.
(3) The browser resolves the IP address of the server.
(4) The browser establishes a TCP connection with the server.
(5) The browser issued a command to take the file: get/chn/yxsz/index.html.
(5) The server responds by sending the file index.html to the browser.
(6) Release the TCP connection.
(7) The browser displays the information used by the index.html.
Features of HTTP
(1)Support Customer service/server (c/s) mode
(2)Simple and fast, when a customer requests a service from the server, it simply transmits the request method and path. The request method commonly has get, POST, HEAD. Each method specifies that the connection to the server is different, because the HTTP protocol is simple, which makes the HTTP server's program smaller, and therefore faster to communicate.
(3) HTTP isNon-connected。 No connection means that HTTP only processes one request at a time, the server finishes processing the customer's request, and receives the customer's answer, i.e., disconnects, which can save the transfer time.
(4) HTTP isNon-stateful。 Stateless means that the HTTP protocol has no memory capability for the transaction, and a lack of status means that the previous information is required for subsequent processing, it must be re-transmitted. This can increase the amount of information that it does not connect to, and on the other hand, the server behaves very quickly without needing the previous information, and it is easier for the server to support a large number of concurrent HTTP requests.
PS: Although HTTP is a non-connected protocol, HTTP uses a connection-oriented Transport layer protocol TCP, which guarantees reliable data transmission, and HTTP does not consider how the data is discarded during transmission and retransmission.
the difference between 2.http/1.0 and http/1.1
The main disadvantage of http/1.0 is that it usesnon-persistent connectionEach request for a document requires twice times the overhead of the RTT. The protocol at this point if a home page has many linked objects (slices), each link needs to establish a new TCP connection, then each link download will incur a 2xRTT overhead.
The http/1.1 protocol solves this problem very well, it uses the persistent connection, the World Wide Web server still maintains this connection for a period of time after sending the response, is the same customer can and this server transmits the subsequent HTTP request message and the response message.
3.HTTP Request Header, response header and status code
Request header (Enter the request header of the simple book, you can open the network view via the Firfox browser through the developer option (shortcut key ctrl+shift+q)).

GET http://www.jianshu.com/
Host:www.jianshu.com
user-agent:mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) gecko/20100101 firefox/47.0
accept:text/html,application/xhtml+xml,application/xml;q=0.9,/; q=0.8
accept-language:zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-encoding:gzip, deflate
referer:https://www.google.com.hk
Cookie: (slightly)
Connection:keep-alive
if-none-match:w/"b4e2a47d84be2df34bb1d5b79be9c040"
Cache-control:max-age=0

The following is the specific meaning:
Get defines the method of the request. There are 8 different methods (listed below).
Host: The hosts and ports in the initial URL.
User-agent: Browser type, this value is useful if the content returned by the servlet is related to the browser type.
Accept: The MIME type acceptable to the browser.
Accept-charset: The acceptable character set of the browser.
Accept-language: The type of language the browser wishes to use when the server is able to provide more than one language version.
Accept-encoding: The way the browser can decode data encoding, such as gzip. The servlet can return a GZIP-encoded HTML page to a browser that supports gzip. In many cases this can reduce download time by 5 to 10 times times.
Referer: Contains a URL from which the user accesses the currently requested page from the page represented by the URL.
Cookie: This is one of the most important request header information that is sent to the Web server along with all the cookie values that are stored under the request domain name.
Connection: Indicates whether a persistent connection is required. If the servlet sees the value here as "keep-alive", or sees the request using an HTTP 1.1 (HTTP 1.1 is persistent by default), it can take advantage of the persistent connection, when the page contains multiple elements (such as applets, pictures), Significantly reduce the time it takes to download. To do this, the servlet needs to send a content-length header in the answer, and the simplest implementation is to write the content to Bytearrayoutputstream first and then calculate its size before formally writing the content.
Cache-control:if-none-match: If the content has not changed return 304 code, the parameter is the server's previously sent ETag, and the server responded to the ETag comparison to determine whether to change.
Cache-control: Specifies the caching mechanism that requests and responses follow.
8 Interpretation of the request method (excerpt from: http://itbilu.com/other/relate/EkwKysXIl.html)
GET
The request displays the resource specified by the request. Generally, the Get method should be used only for reading data, not for non-idempotent operations that produce side effects. The Get method requests the specified page information and returns the response body, and get is considered an unsafe method because the Get method is accessed arbitrarily by the network spider.
HEAD
method, like the Get method, is a request to the server for a specified resource. However, the server responds to the head
The request does not return the content part of the resource, that is, the response body. In this way, we can get the server's response header information without transmitting the entire content. The head method is often used by clients to view the performance of the server.
POST
The request submits data to the specified resource and requests the server to process it, such as: Form data submission, file upload, etc., and the request data is included in the request body. The Post method is a non-idempotent method, because this request may create new resources or/and modify existing resources.
PUT
The request will upload its latest content to the specified resource location, and the Put method is a idempotent method. This method allows the client to transfer the most recent data from the specified resource to the server in place of the specified resource's content.
DELETE
The request is used to request the server to delete the resource identified by the requested URI (Uniform Resource Identifier, Uniform Resource Identifier). Deletes the specified resource after the delete request, and the Delete method is idempotent
Of
CONNECT
This method is reserved by the http/1.1 protocol and is able to change the connection to a proxy server for the pipeline mode. A link to an SSL-encrypted server is typically used to communicate with a non-encrypted HTTP proxy server.
OPTIONS
The request is similar to head and is typically used for client View server performance. This method requests the server to return all HTTP request methods supported by the resource, which uses the '' instead of the resource name, send an options request to the server to test if the server is functioning properly. When a JavaScript XMLHttpRequest object is shared with a cors cross-domain resource, the options method is used to send a sniffer request to determine whether there is access to the specified resource. Allow
*
TRACE
The requesting server echoes the request information it receives, which is used primarily for testing or diagnosing HTTP requests.
*
Response header (also in the request Pinterest first page of the response header

Cache-control:max-age=0, Private, Must-revalidate
connection:keep-alive
content-encoding: Gzip
content-type:text/html; charset=utf-8
Date:sun, June 15:29:41 GMT
etag:w/ e9a43aabd740855cd3fe0097faf6180d "
Server:nginx
Set-cookie: (slightly)
vary:accept-encoding
X-request-id: ce26a795-7e99-4959-a498-45f689471d7f
x-runtime:0.596683
X-content-type-options:nosniff
X-frame-options:deny
X-xss-protection:1; mode=block

CACHE-CONTROL Specifies the caching mechanism that requests and responses follow.
Connection: Indicates whether a persistent connection is required.
The encoding (Encode) method of the Content-encoding document. The content type specified by the Content-type header can be obtained only after decoding. Using gzip to compress documents can significantly reduce the download time of HTML documents.
Content-type indicates what MIME type the subsequent document belongs to. The servlet defaults to Text/plain, but it usually needs to be explicitly specified as text/html. Because Content-type is often set up, HttpServletResponse provides a dedicated method Setcontenttyep.
Date the current GMT time. You can use Setdateheader to set this header to avoid the hassle of converting the time format.
The current value of the entity label for the ETAG request variable.
Server name. The servlet generally does not set this value, but is set by the Web server itself.
Set-cookie sets the Cookie associated with the page.
Vary tells the downstream agent whether to use the cache response or request from the original server
For more detailed request header and response header information, please refer to: HTTP header detailed
*
Status Code
1XX: Represents the notification information, such as a request received or being processed.
2XX: Indicates success, as received or known.
3XX: Indicates redirection and further processing is required to complete.
4XX: Indicates a customer error, such as an incorrect syntax in the request or a failure to complete.
5XX: Indicates a server error, such as server failure cannot complete the request.

httpurlconnection in 4.Android
The connection in Android is mainly done by HttpURLConnection, and the following is going to behttpurlconnection use, get and post pass parameters, multi-threaded downloadThree ways to see the use of httpurlclient:
(1) httpurlconnection use format:
URL url = new URL("http://localhost:8080/TestHttpURLConnectionPro/index.jsp"); //将地址转换为URL
URLConnection rulConnection = url.openConnection(); // 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类的子类HttpURLConnection,故此处最好将其转化为HttpURLConnection类型的对象 HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
to set the connection parameters for Httpurlclient:
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在。http正文内,因此需要设为true, 默认情况下是false; httpUrlConnection.setDoOutput(true); //设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true); // Post 请求不能使用缓存 httpUrlConnection.setUseCaches(false); // 设定传送的内容类型是可序列化的java对象 // (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); // 设定请求的方法为"POST",默认是GET httpUrlConnection.setRequestMethod("POST"); // 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, httpUrlConnection.connect();
For the specific use of httpurlconnection in the code, see below are the same usage, read it and understand.
(2) Get and post mode pass parameters
Get mode
The key to passing a parameter using get is the URL, which can be seen in the code where we append some data to the URL, and actually the Get method is to pass the parameter by appending the data to the URL, so it is not safe to use this method.
private void doGet(){ try { url = url + "?name=" + URLEncoder.encode(name,"utf-8") + "&age=" + age; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { URL httpUrl = new URL(url); //新建URL对象 HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();//打开一个连接 conn.setRequestMethod("GET");//设置请求方法为GET conn.setReadTimeout(5000);//设置从服务器读取数据的超时限制为5秒 BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream()));//获取服务器传递的数据输入流 String str; StringBuffer sb = new StringBuffer(); //存储读取的数据 while((str = reader.readLine()) != null){//读取数据 sb.append(str); } System.out.println("result:"+sb.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Post Mode
Post passes parameters in a different way than get, which writes the passed data to the body of the request.
private void doPost(){ try { URL HttpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) HttpUrl.openConnection(); conn.setRequestMethod("POST"); conn.setReadTimeout(5000); OutputStream out = conn.getOutputStream(); //新建输出流对象 String content = "name="+name+"&age="+age;//传递对象 out.write(content.getBytes());//将传递对象转为字符流写入输出流中 //下面是对于服务器返回数据的处理 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String str; while((str=reader.readLine())!=null){ sb.append(str); } System.out.println(sb.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
(3) Multi-threaded Download

PublicClass DownLoad {Private Executor ThreadPool = Executors.newfixedthreadpool (3);Private Handler Handler;PublicDownLoad(Handler Handler) {This.handler = handler;}StaticClass Downloadrunnable implements Runnable {Private String URL;Private String FileName;PrivateLong start;PrivateLong end;Private Handler Handler;PublicDownloadrunnable(String url,string FileName,Long Start,Long End,handler Handler) {This.url = URL;This.filename = FileName;This.start = start;This.end = end;This.handler = handler; } @OverridePublicvoidRun() {try {URL Httpurl =New URL (URL); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Range","Bytes=" +start+"-" +end); Conn.setreadtimeout (5000); Randomaccessfile Access =New Randomaccessfile (New File (FileName),"RWD"); Access.seek (start); InputStream in = Conn.getinputstream (); Byte[] B =New byte[1024*4];int len=0;while ((Len=in.read (b))!=-1) {Access.write (b),0,len); }if (access!=null) {access.close ();}if (in!=null) {in.close ();} Message msg =New Message (); Msg.what =1; Handler.sendmessage (msg); }catch (IOException e) {e.printstacktrace ();}}}PublicvoidLoadFile(String URL) {try {URL Httpurl =New URL (URL); HttpURLConnection conn = (httpurlconnection) httpurl.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000);int count = Conn.getcontentlength ();int block = count/3; String fileName = getfilename (URL); File parent = Environment.getexternalstoragedirectory (); File download =New File (Parent,filename);for (int i=0;i<3;i++) {long start = I*block; long end = (I+1) *block-1; if (I==2) {end = count;} Downloadrunnable runnable = new downloadrunnable (Url,download.getabsolutepath (), Start, End,handler); Threadpool.execute (runnable); }} catch (IOException e) {e.printstacktrace ();}} public String getFileName (String URL) {return url.substring (Url.lastindexof (1);           

}
Reference:
(1) Web courses HTTP communication in Android
(2) HTTP request method:, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE
(3) HTTP response header information and request header information detailed
(4) HTTP Header Detailed

HTTP Communication in Android

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.