Brief analysis of Httpcient

Source: Internet
Author: User

The HTTP protocol is probably the most widely used and most important protocol on the Internet now, and more and more Java applications need to access network resources directly through the HTTP protocol. While the basic functionality of accessing the HTTP protocol has been provided in the JDK's java.net package, the JDK library itself provides a lack of functionality and flexibility for most applications. HttpClient is a sub-project under Apache Jakarta Common to provide an efficient, up-to-date, feature-rich client programming toolkit that supports the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol.

First, the realization function

1, the implementation of all HTTP methods, read Web content (Get,post,put,head, etc.)

2. Support Automatic Steering

3. Support HTTPS Protocol

4, support proxy server, etc.

For more functions, please refer to httpclient official documentation

1. Read Web page (HTTP/HTTPS) content

The steps are as follows: first create an instance of an HTTP client (HttpClient), then select the method to commit is get or post, and finally execute the commit on the HttpClient instance, and finally read the results from the server feedback from the selected submission method.

/*** The simplest HTTP client to demonstrate access to a page via get or post * @authorLiudong*/         Public classSimpleClient { Public Static voidMain (string[] args)throwsIOException {HttpClient client=NewHttpClient (); //setting the proxy server address and port//client.gethostconfiguration (). SetProxy ("Proxy_host_addr", Proxy_port); //using the GET method, if the server needs to be connected over HTTPS, you only need to change the HTTP in the URL below to HTTPSHttpMethod Method=NewGetMethod ("http://java.sun.com"); //using the Post method//HttpMethod method = new Postmethod ("http://java.sun.com");Client.executemethod (method); //status returned by the print serverSystem.out.println (Method.getstatusline ()); //Print the returned informationSystem.out.println (method.getresponsebodyasstring ()); //Release Connectionmethod.releaseconnection (); }        }

2. Submit data using Post

HttpClient uses a separate HttpMethod subclass to process the file upload, this class is Multipartpostmethod, the class has encapsulated the file upload details, we have to do is just to tell it we want to upload the full path of the file, Here's a code for two types of analog uploads

2.1. Simulate upload URL file (This method is also suitable for normal POST request):

   /** * Upload URL file to the specified URL * @param fileUrl upload image URL * @param posturl upload path and parameters, note that some Chinese parameters need to use pre-coding Eg:URLEncoder.enco De (AppName, "UTF-8") * @return * @throws IOException */public static string Douploadfile (string posturl) t        Hrows IOException {if (Stringutils.isempty (posturl)) return null;        String response = "";        Postmethod Postmethod = new Postmethod (PostURL);            try {HttpClient client = new HttpClient (); Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (50000);//Set connection time int STA            Tus = Client.executemethod (Postmethod);                if (status = = Httpstatus.sc_ok) {InputStream InputStream = Postmethod.getresponsebodyasstream ();                BufferedReader br = new BufferedReader (new InputStreamReader (InputStream));                StringBuffer StringBuffer = new StringBuffer ();                String str = ""; WhiLe ((str = br.readline ()) = null) {stringbuffer.append (str);            } response = Stringbuffer.tostring ();            } else {response = "fail";        }} catch (Exception e) {e.printstacktrace ();        } finally {//release connection postmethod.releaseconnection ();    } return response; }

  

2.2. Upload the analog file to the specified location

  /*** Upload file to specified URL *@paramfile *@paramURL *@return     * @throwsIOException*/     Public StaticString douploadfile (file file, string url)throwsIOException {String response= ""; if(!file.exists ()) {            return"File NOT Exists"; } Postmethod Postmethod=Newpostmethod (URL); Try {            //----------------------------------------------            //Filepart: The class used to upload a file, file that is to be uploadedFilepart FP=NewFilepart ("File", file); part[] Parts={FP}; //for MIME-type requests, HttpClient recommends full mulitpartrequestentity packagingmultipartrequestentity MRE=Newmultipartrequestentity (Parts, Postmethod.getparams ());            Postmethod.setrequestentity (MRE); //---------------------------------------------HttpClient Client=NewHttpClient (); Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (50000);//The maximum connection time-out is set here because the file to be uploaded may be large            intStatus =Client.executemethod (Postmethod); if(Status = =HTTPSTATUS.SC_OK) {InputStream InputStream=Postmethod.getresponsebodyasstream (); BufferedReader BR=NewBufferedReader (NewInputStreamReader (InputStream)); StringBuffer StringBuffer=NewStringBuffer (); String Str= "";  while(str = br.readline ())! =NULL) {stringbuffer.append (str); } Response=stringbuffer.tostring (); } Else{Response= "Fail"; }        } Catch(Exception e) {e.printstacktrace (); } finally {            //Release Connectionpostmethod.releaseconnection (); }        returnresponse; }

3. Handling page Redirection

The Response.sendredirect method in Jsp/servlet programming is to use the redirection mechanism in the HTTP protocol. It differs from the <jsp:forward ...> in the JSP in that the latter is a jump in the server to implement the page, that is, the application container loads the content of the page to jump and return to the client, while the former is to return a status code, the possible values of these status codes are shown in the table below, The client then reads the URL of the page that needs to jump to and reloads the new page. Is such a process, so when we are programming it is necessary to determine whether the return value is a value in the following table by using the Httpmethod.getstatuscode () method to determine if a jump is required. If you have confirmed that a page jump is required, you can obtain a new address by reading the Location property in the HTTP header.


The following code snippet shows how to handle page redirection

Client.executemethod (POST); System.out.println (Post.getstatusline (). toString ());p ost.releaseconnection ();//Check if redirection is being redirectedintStatusCode =Post.getstatuscode ();if((statuscode = = httpstatus.sc_moved_temporarily) | | (statuscode = = httpstatus.sc_moved_permanently) | |(StatusCode==httpstatus.sc_see_other) | | (StatusCode = =httpstatus.sc_temporary_redirect)) {//read the new URL addressHeader Header=post.getresponseheader ("Location"); if(header!=NULL) {Stringnewuri=Header.getvalue (); if((newuri==NULL)|| (Newuri.equals ("")) Newuri="/"; Getmethodredirect=Newgetmethod (Newuri);         Client.executemethod (redirect); System.out.println ("Redirect:" +redirect.getstatusline (). toString ());   Redirect.releaseconnection (); }ElseSystem.out.println ("Invalid Redirect");}

We can write our own two JSP pages, one of which is redirected to another page using the Response.sendredirect method to test the example above.

Brief analysis of Httpcient

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.