HTTP protocol, basic concept of HTTP protocol

Source: Internet
Author: User

HTTP protocol Learning Focus: The basic concept of HTTP protocol, request response model, the different methods of submitting requests, response status judgment, get response and resolution response, data download implementation method, data upload implementation method, request header details, response header details and so on the HTTP protocol learning, Recommended two links: http://www.cnblogs.com/TankXiao/archive/2012/02/13/2342672.htmlhttp://blog.csdn.net/gueter/article/ details/1524447. Using the HTTP protocol to access the network: The WebView control in Android has been in the background to help us handle the process of sending HTTP requests, receiving service responses, parsing the return data, and the final page showing these steps, but because it's encapsulated so well, Instead of visually seeing how the HTTP protocol works. So the next step is to get a more in-depth look at this process by manually sending HTTP requests. There are generally two ways to send HTTP requests on Android: HttpURLConnection and Httpcient. Let's learn httpcient first. Third, Httpcient:httpclient is the Apache Open Source organization provides HTTP network access interface (an open source project), as can be seen from the name, it is a simple HTTP client (not a browser), can send HTTP requests, accept HTTP response. But does not cache the server's response, cannot execute the HTTP page to check in the embedded JS code, naturally also does not have the page content to parse, the processing, these all need the developer to complete. Now that Android has successfully integrated httpclient, developers can use HttpClient directly in Android projects to submit requests and accept responses to Web sites, and if other Java projects are used, they need to be introduced into the appropriate jar package. HttpClient can be downloaded on the official website. Website Link: http://hc.apache.org/downloads.cgiHttpClient is actually a interface type, httpclient encapsulates the HTTP requests, authentication, connection management, and other features that an object needs to perform. Since HttpClient is an interface, you cannot create an instance of it. From the documentation, HttpClient has three known implementation classes: Abstracthttpclient, Androidhttpclient, Defaulthttpclient, and will find an implementation specifically for Android appsClass Androidhttpclient, of course, the use of regular defaulthttpclient can also achieve functionality. From the two Class pack all in position you can see the difference, Androidhttpclient is defined under the Android.net.http.AndroidHttpClient package and belongs to Android native HTTP access, while defaulthttpclient is defined in ORG.APACHE.HTTP.IMPL.CLI Ent. Under the Defaulthttpclient package, it belongs to the Apche project support. Androidhttpclient does not have a public constructor, only the static method Newinstance () method to obtain the Androidhttpclient object. To put it simply, sending requests and receiving responses with HttpClient is simple and requires only five steps: (remember) to create a HttpClient object that represents the client. Creates an object that represents the request, creates a HttpGet object if a GET request needs to be sent, and creates a HttpPost object if a POST request needs to be sent. Note: For the parameters that send the request, get and post use different ways, get method can use stitching string, the parameters are stitched at the end of the URL, the Post method needs to use the setentity (httpentity entity) method to set the request parameters. The Execute (httpurirequest request) of the HttpClient object is called to send the request, and after the method is executed, the HttpResponse object returned by the server is obtained. The data that the server sends back to us is in this httpresponse corresponding. Call HttpResponse's corresponding method to get the server's response header, response content, and so on. Check that the appropriate status is normal. Server sent to the client corresponding, there is a corresponding code: the corresponding code is 200, normal, the corresponding code is 404, the client error, the corresponding code is 505, server-side error. Get data from the corresponding object//Send request with HttpClient, divided into five steps//First step: Create HttpClient object HttpClient httpcient = new Defaulthttpclient ();//Second step  : Create the object that represents the request, the parameter is the server address httpget HttpGet = new HttpGet ("http://www.baidu.com"); try {//Third step: Execute the request to get the corresponding object returned by the server                   HttpResponse HttpResponse = Httpcient.execute (httpget);///Fourth: Check that the appropriate status is normal: Check the value of the status code is 200 for normal if (httprespons E.getstatusline (). Getstatuscode () = = 200) {//Fifth step: Remove the data from the corresponding object and place it in the entity httpentity entity = Httpre                        Sponse.getentity (); String response = entityutils.tostring (entity, "utf-8"/Sub-thread: Send the user name, password information to the server via the Get method 61class GetThread extends Thread {62 The String name; a String pwd; 66public getthread (string name, string pwd) {67this.name = name; 68this.pwd = pwd; @Override 72publicvoid run () {73//sends the request with HttpClient, divided into five steps 74//the first step: Create HttpClient object, HttpClient HttpClient = new Defaulthtt Pclient (); 76//Note, in the following line, I previously put the link in the "Test" mistakenly written "text", resulting in the adjustment of the bug for a long time did not get out, it is really a waste of a String URL = "Http://192.168.1.112:8080/test." Jsp?name= "+ name+" &password= "+ pwd; 78//Second Step: Create the object that represents the request, the parameter is the server address of the access httpget HttpGet = new HttpGet (URL);          80try {81//Step three: Execute the request to get the corresponding object returned by the server 82       HttpResponse response = Httpclient.execute (HttpGet); 83//Fourth Step: Check that the appropriate status is normal: Check the value of the status code is 200 for normal 84if (Response.getstatusline (). Getstatuscode () = = 200) {85//Fifth step: Extract data from the corresponding object, Put into the entity httpentity entity = response.getentity (); BufferedReader reader = new BufferedReader (88new InputStreamReader (Entity.getcontent ())); The String result = Reader.readline (); LOG.D ("HTTP", "GET:" + result);        (Exception e) {e.printstacktrace (); 94} 95 96        } 97} 98 99//: Use the Post method to send a user name, password, and other data to the server 100class Postthread extends Thread {101102 String name;103        String Pwd;104105public postthread (string name, string pwd) {106this.name = Name;107this.pwd = pwd;108}109110 @Override111publicvoid run () {HttpClient HttpClient = new Defaulthttpclient (); 113 Strin G URL = "http://192.168.1.112:8080/tEst.jsp "; 114//second step: Generate a Request object using the Post method HttpPost HttpPost = new HttpPost (URL); The 116//namevaluepair object represents a key value to be sent to the server For 117 Namevaluepair Pair1 = new Basicnamevaluepair ("name", name); 118 Namevaluepair Pair2 = new Basi Cnamevaluepair ("password", pwd); 119//put the prepared key-value pairs of objects in a list of arraylist<namevaluepair> pairs = new Array List<namevaluepair> (); 121 pairs.add (PAIR1); 122 Pairs.add (PAIR2); 123try {124//creates an object representing the request body (note that the request Httpentity requestentity = new urlencodedformentity (pairs); 126//Place the request body in the Request Object 127 HTTP  Post.setentity (requestentity); 128//Execute Request object 129try {130//Step three: Execute the Request object, get the corresponding object returned by the server 131 HttpResponse response = Httpclient.execute (HttpPost); 132//Fourth Step: Check that the appropriate status is normal: Check the value of the status code is 200 for normal 133if (Response.getstatusline (). Getstatuscode                         () = = 200) {134//Fifth step: Take the data from the corresponding object and put it into the entity 135 httpentity entity = response.getentity (); 136 BufferedReaderreader = new BufferedReader (137new InputStreamReader (Entity.getcontent ())) 138 String result = Rea Der.readline (); 139 Log.d ("HTTP", "POST:" + result);}141} C Atch (Exception e) {142 e.printstacktrace (); 143}144} catch (Exception e) { 145 e.printstacktrace (); 146}147}148}149

HTTP protocol, basic concept of HTTP protocol

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.