Brief introduction and use of Finalhttp

Source: Internet
Author: User

Http://blog.csdn.net/zhaokaiqiang1992/article/details/30291259?utm_source=tuicool

In a previous article, we briefly introduced the use of the next finalbitmap, this article will continue to introduce the use of the Afinal development framework, this time the protagonist is finalhttp.

Finalhttp, as the name implies, is a class used to implement network communication between client and server, this class is mainly through the encapsulation of Apache's HttpClient Open source project, realizes the HTTP, https protocol "GET" and "Post" two kinds of request mode, As well as put, delete, download and other functions, we mainly introduce the use of FINALHTTP implementation and the server "GET" and "Post" two ways of interaction.

PrivateStaticFinal Threadfactory sthreadfactory =new threadfactory () { private final atomicinteger mCount = new atomicinteger (1);  public Thread newthread (Runnable r) {  thread tread = new Thread (R, " Finalhttp # "+ mcount.getandincrement ());   Tread.setpriority (thread.norm_priority-1);  return tread;}}; private static final Executor Executor = Executors.newfixedthreadpool (Httpthreadcount, sthreadfactory);         
First, Finalhttp uses the thread pool to provide an asynchronous load of the request, with the default of starting 3 fixed threads. And
Tread.setpriority (thread.norm_priority-1);
This code sets the priority of these threads lower than the normal thread and is not currently known for any consideration.

In addition, in the Finalhttp constructor, many properties are initialized, including adding the request header, setting timeout time, setting the number of retries, etc., the code is more, please read the reader himself.

Finalhttp has a very good encapsulation of "GET" and "Post", so it's very easy to use, so let's take a brief look at the use of finalhttp.

First, we can pass

Finalhttp http = new finalhttp ();

You can easily get to a Finalhttp object.

If we want to implement the simplest get request, such as we use Get method, request Baidu homepage, we can do this

Publicvoid get (view view) {    This is the simplest get request, preceded by the request address, do not forget to add HTTP//  The following is a callback function, the more commonly used methods are as follows two Http.get ("Http://www.baidu.com",New Ajaxcallback<string> () {   When our request fails, it is called, Errorno is the error code of the server after the request fails, and strmsg is the error message.   @Override   Publicvoid OnFailure (Throwable t,int Errorno, String strMsg) {    Super.onfailure (t, Errorno, STRMSG);   LOG.D (TAG, STRMSG);  }   //if the request succeeds, call this callback function, T is the string information returned by the server     @Override    public void onsuccess (String t) {    super.onsuccess (t);     LOG.D (TAG, t);   } });                /span>               
We can see that with the Finalhttp implementation get network request, we do not need their own thread, because the framework has been encapsulated, in the internal to the thread we open, to implement the network asynchronous call. In fact, there is not only get method, there is a getsync, this method is not the request of another thread, so, if we want to use Getsync this method, we need to open the thread ourselves, otherwise in the latest version of the main thread to open the network service, will throw an exception.

Of course, this is only the simplest use of Get methods, Finalhttp provides a total of three overloads of the Get method, the code is as follows

------------------GET Request-----------------------  PublicvoidGet (String URL, ajaxcallback<? extends object> CallBack) {  Get (URL,NULL, callBack);} PublicvoidGet (String URL, ajaxparamsparams, ajaxcallback<? Extends Object> callBack) { SendRequest (HttpClient, HttpContext,New HttpGet (geturlwithquerystring (URL,params)), null, callBack); }  public  void get (String URL, header[] headers, ajaxparams params, ajaxcallback <? Extends Object> callBack) {  Httpurirequest request = new httpget (geturlwithquerystring (URL, params));   if (headers! = null) request.setheaders (headers);   SendRequest (HttpClient, HttpContext, request,  NULL, callBack);                /span>      
The second method adds the Ajaxparams parameter, which is responsible for setting the request value of the GET request, which is the &key1=values1 &key2=values2 this form of request parameter after the URL address of the GET request. Internal is actually achieved through map<string,string>, so the use is the same as map. But this ajaxparams is more powerful, we can add a lot of things, such as files, streams and so on.

The third method adds a header array, which is used to set the requested header information, and the other is the same as the above two.

Public Object getsync (String URL) {    Return Getsync (URL,NULL);} Public Object getsync (String URL, ajaxparamsparams) { Httpurirequest request =New HttpGet (geturlwithquerystring (URL,params));  return sendsyncrequest (HttpClient, HttpContext, Request, null); }   public Object getsync (String URL, header[] headers, ajaxparams params) {  Httpurirequest request = new httpget (geturlwithquerystring (URL, params));   if (headers! = null) Request.setheaders (headers);   return sendsyncrequest (HttpClient, HttpContext, Request, null);                /span>        

This is the implementation of the Getsync, in fact, and the Get method, just because you need to separate the thread, so there is no callback function this parameter, using the same method.

Let's take a look at the post method used.

------------------The POST request-----------------------  Publicvoid post (String URL, ajaxcallback<? extends object> CallBack) {  Post (URL,NULL, callBack);} Publicvoid post (String URL, ajaxparamsparams, ajaxcallback<? Extends Object> callBack) { Post (URL, paramstoentity (params),NULL, callBack);} Publicvoid post (string url, httpentity entity, String contentType, ajaxcallback<? extends object> CallBack) { SendRequest (HttpClient, HttpContext, Addentitytorequestbase (New HttpPost (URL), entity), ContentType, CallBack);} Public <T>void post (String URL, header[] headers, ajaxparamsparams, String contenttype,ajaxcallback<t> callBack) { Httpentityenclosingrequestbase request =New HttpPost (URL);  IfParams! =NULL) request.setentity (paramstoentity (params));  if (headers! = null) request.setheaders (headers);  SendRequest (HttpClient, HttpContext, request, ContentType, callBack); } public void post (String URL, header[] headers, httpentity entity, String contenttype,ajaxcallback<? Extends Object> callBack) {  Httpentityenclosingrequestbase request = Addentitytorequestbase (new httppost (URL), entity);   if (headers! = null) request.setheaders (headers);   SendRequest (HttpClient, HttpContext, request, ContentType, callBack); Span class= "indent" >             

In the above code, we can see that the post is used almost the same as the Get method, except that it adds a few new parameters.

Here is a simple example of calling the Post method

Publicvoid post (view view) {  Http.post ("Http://www.baidu.com",New Ajaxcallback<string> () {   @Override   Publicvoid OnFailure (Throwable t,int Errorno, String strMsg) {    Super.onfailure (t, Errorno, STRMSG);    LOG.D (TAG, STRMSG);   }    @Override    span class= "keyword" >public void onsuccess (String t) {    super.onsuccess (t);     LOG.D (TAG, t);   } });      

We can add files through Ajaxparams, then we can use the Post method to submit files to the server for uploading files.

Ajaxparams params = new Ajaxparams ();              Params.put ("username", "Michael Yang");              Params.put ("Password", "123456");              Params.put ("Email", "[email protected]"); Params.put ("Profile_picture", New File ("/mnt/sdcard/pic.jpg")); Upload file Params.put ("Profile_picture2", InputStream); Upload data stream params.put ("Profile_picture3", New Bytearrayinputstream (bytes)); Submit byte stream

Brief introduction and use of Finalhttp

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.