The Android andbase framework uses encapsulated functions to complete HTTP requests (c) _android

Source: Internet
Author: User
Tags http post throwable

This article is for the Andbase framework learning the third note, want to understand the andbase framework of friends can read this article, we learn together.

Learning content:

1. Using the Andbase framework to implement the non-parametric HTTP GET request ...

2. Implement a parameter HTTP POST request using the Andbase framework ...

3. Implement a parameter HTTP GET request using the Andbase framework ...

The Andbase framework provides us with some relevant methods to use to complete HTTP network requests ... The general is a package of HTTP requests, but personally think that the network request this module is more recommended to use the volley framework. Landlord compared the two frame in the source code ... Volley more places are encapsulated in an interface with an abstract method, and then expose the interface, and other classes need to implement an internal abstract method while implementing the interface ... And Andbase is the way to use inheritance. Inherit the parent class ... The implementation class overrides the encapsulated method to do the next step in an overridden way ...

Compared to the two network requirements of the source code, volley source code is better than the writing ... Volley is Google launched, and for the only network request this module ... The same andbase is also very excellent, is the domestic cow wrote a heavyweight framework, involving a very wide range of modules, or very useful ...

1. Using the Andbase framework to implement a non-parametric HTTP GET request

General network request if not related to the changes in data information, that is, not involved in some security issues, can use get way to complete the network request ... Get request is also divided into ginseng and parameterless, give me the feeling of the general can be used to upload resource data to the server ... Let me introduce you to the no-parameter GET request ... Or first from the source of the place to see ...

The source code is called by first using the Abhttputils.get () function call ... But it doesn't matter ... Through this approach to the Abhttpclient class inside ... Execute the following code ... Whether there is a parameter or no parameter. Will call this method ... The second argument passes NULL when no argument is made ...

public void get (final String url,final abrequestparams params,final abhttpresponselistener responselistener) {
  
  Responselistener.sethandler (New Responderhandler (Responselistener));
  Executorservice.submit (New Runnable () {public 
   void run () {
    try {
     doget (url,params,responselistener);
    } catch (Exception e) { 
     e.printstacktrace ();}}}     
  );    
 

We can see that this function first sends the message through the handler ... A thread pool is opened at the same time to submit the current request, and the Doget () method is executed at the end, while the handler always handles the Responselistener message. The source code process for the Doget () method is as follows

private void Doget (String url,abrequestparams params,abhttpresponselistener responselistener) {try {response
    
    Listener.sendstartmessage (); if (!debug &&! Abapputil.isnetworkavailable (Mcontext)) {Responselistener.sendfailuremessage (Abconstant.connect_failure_code,
     Abconstant.connectexception, New Abappexception (abconstant.connectexception));
    Return
    The//httpget Connection object if (params!=null) {url = params.getparamstring ();///////If there is a parameter, get the relevant parameter ...} HttpGet HttpRequest = new HttpGet (URL);
    
    Define the Connection object ...
    
    Basichttpparams httpparams = new Basichttpparams ();
    Timeout for connection taking from connection pool, set to 1 sec connmanagerparams.settimeout (Httpparams, default_socket_timeout);
    Connmanagerparams.setmaxconnectionsperroute (Httpparams, New Connperroutebean (default_max_connections));
    Connmanagerparams.setmaxtotalconnections (Httpparams, default_max_connections); The timeout for reading response data httpconnectionparams.setsotimeout (Httpparams, Default_socket_timeouT);
    Httpconnectionparams.setconnectiontimeout (Httpparams, default_socket_timeout);
    Httpconnectionparams.settcpnodelay (Httpparams, true);
    Httpconnectionparams.setsocketbuffersize (Httpparams, default_socket_buffer_size);
    Set protocol version ...
    Httpprotocolparams.setversion (Httpparams, httpversion.http_1_1);
    Httpprotocolparams.setuseragent (Httpparams, String.Format ("andbase-http/%s (http://www.418log.org/)", 1.0));
    
    Set request parameter Httprequest.setparams (httpparams); 
    Get HttpClient object HttpClient httpclient = new Defaulthttpclient (); 
    Request HttpClient, obtain HttpResponse httpresponse HttpResponse = Httpclient.execute (HttpRequest);
    
    The request succeeded int statusCode = Httpresponse.getstatusline (). Getstatuscode ();
    Gets the returned string httpentity mhttpentity = Httpresponse.getentity (); if (StatusCode = = HTTPSTATUS.SC_OK) {if (Responselistener instanceof abstringhttpresponselistener) {String cont
      ent = entityutils.tostring (mhttpentity); ((AbstriNghttpresponselistener) responselistener). Sendsuccessmessage (StatusCode, content); }else if (responselistener instanceof Abbinaryhttpresponselistener) {readresponsedata (mHttpEntity, (
     Abbinaryhttpresponselistener)) (Responselistener)); }else if (responselistener instanceof Abfilehttpresponselistener) {//get filename String filename = abfileutil.getfile
      Namefromurl (URL, httpresponse);
     Writeresponsedata (Mhttpentity,filename, (Abfilehttpresponselistener) responselistener));
     }}else{String content = entityutils.tostring (mhttpentity);
    Responselistener.sendfailuremessage (StatusCode, Content, new Abappexception (abconstant.unknownhostexception));
   } catch (Exception e) {e.printstacktrace ();
  Send Failure Message responselistener.sendfailuremessage (Abconstant.untreated_code,e.getmessage (), New Abappexception (e));
  }finally{Responselistener.sendfinishmessage (); }
 }

With the above source code call process is actually very clear.

Whether the Doget () method or the Dopost () method pattern is basically the same, it is necessary to first establish a Connection object, HttpGet or HttpPost. The difference is that a parameter get request joins the params directly behind the URL, and the POST request requires the Entity data. Add params to the Entity data that we deliver. Set up the connection process and read the data in the process of the relevant parameters, such as Time out, the use of HTTP version, set useragent, etc. ... After setting up, execute request get response ...

A process of judgment is involved in the middle. Determine what type of data the response data is returned to, whether it is a basic string type, or a byte type associated with a picture or video, or a file type associated with files ... By the judgment of the relevant types, the implementation of different methods, although the method is not the same, but the final purpose is the same, are to encapsulate the entity data ... After the package is finished, call Sendsuccessmessage and handler automatically go back to processing message ... Finally, call the Onsuccess method. Return data to the client ...

Or look at the actual calling process:

Non-parametric GET request scheduling, where appropriate monitoring needs to be set:

public void Fileclick (View v) {
 url= "yun_qi_img/imageview.jpg";
 GetView ();
 Httputil.get (URL, new Fileresponselistener (this, this, V,max_tv,num_tv,progressbar));
 Getresponselistener.java

An overriding procedure for listening to responses ... The network request can be completed by url+ related listening for the request, and the request data should be processed ... This completes the download of a picture data, and then by encapsulating the data, it becomes a bitmap. This allows you to display on the control ...

Package com.example.andbasehttp;

Import Java.io.File;
Import Android.app.AlertDialog;
Import Android.content.Context;
Import Android.content.DialogInterface;
Import Android.content.DialogInterface.OnClickListener;
Import Android.graphics.Bitmap;
Import Android.view.View;
Import Android.widget.ImageView;
Import Android.widget.TextView;
Import com.ab.activity.AbActivity;
Import Com.ab.http.AbFileHttpResponseListener;
Import Com.ab.util.AbFileUtil;

Import Com.ab.view.progress.AbHorizontalProgressBar;
 public class Fileresponselistener extends abfilehttpresponselistener{private int max=100;
 private int progress=0;
 Private abactivity activity;
 private context;
 Private Alertdialog Dialog;
 Private view view;
 Private TextView Max_tv,num_tv;
 
 Private Abhorizontalprogressbar ProgressBar; Public Fileresponselistener (abactivity activity,context context,view V,textview V1,textview,
  Abhorizontalprogressbar ProgressBar) {this.activity=activity;
 This.context=context; This.view=v;
  THIS.MAX_TV=V1;
  This.num_tv=v2;
 This.progressbar=progressbar;
  @Override public void onsuccess (int statusCode, file file) {Bitmap bitmap=abfileutil.getbitmapfromsd (file);
  ImageView view=new ImageView (context);
  View.setimagebitmap (bitmap); Activity.showdialog ("Return result", view, New Onclicklistener () {@Override public void OnClick (Dialoginterface dialog,
 int which) {//TODO auto-generated Method stub}}); @Override public void onfailure (int statusCode, String content,throwable error) {Activity.showtoast (error.tostring
 ());
  @Override public void OnStart () {Max_tv.settext (progress+ "/" +string.valueof (max));
  Progressbar.setmax (max);
  Progressbar.setprogress (progress);
 Dialog=activity.showdialog ("Downloading", view); @Override public void onprogress (int byteswritten, int totalsize) {Max_tv.settext (byteswritten/(Totalsize/max) + "/"
  +max);
 Progressbar.setprogress (byteswritten/(Totalsize/max)); } @Override Public void OnFinish () {dialog.cancel ();
 Dialog=null;

 }
}

2. Implement a parametric HTTP POST request using the Andbase framework

In fact, the way the call is the same, except that the post request needs to pass the relevant parameters ... Use a parameter POST request ... Here is to pass the relevant parameters to a JSP to complete the verification of the data information ...

public void Postclick (View v) {
 url= "http://192.168.199.172:8080/JSP/post.jsp";
 Params=new abrequestparams ();
 Params.put ("name", "darker");
 Params.put ("Password", "49681888");
 Httputil.post (URL, params, new Postresponselistener (this));
}

Here I will not paste the Postresponselistener code ... Paste the code for the JSP page. The relevant JSP code is as follows ... The JSP code here is very simple. And also used in front of the use of volley. JSP pages we can write their own more complex, then we can achieve more functions ...

<%
 String name=request.getparameter ("name");
 String password=request.getparameter ("password");
 if ("Darker". Equals (name) && "49681888". Equals (password)) {
  out.println ("Receive name is:" +name);
 Out.println ("Receive password is:" +password);%>
 Your message are right!
 <%}else{
  out.println ("Receive name is:" +name);
 Out.println ("Receive password is:" +password);%>
 Your message are wrong!
 <%}%> 

3. Implement a parameter HTTP GET request using the Andbase framework

A parameter get request is generally used for file, data resource upload ... Pass the uploaded resource and name as parameters to the server. There is no security issue here. Therefore, you can use a GET request with parameters ... Upload file to server here. Need to add related parameters ...

public void Fileloadclick (View v) {
  url= "http://192.168.199.172:8080";
  Abrequestparams params = new Abrequestparams (); 
  File pathroot = Environment.getexternalstoragedirectory ();
  String path = Pathroot.getabsolutepath ();
  File File1 = new file (path+ "/download/cache_files/aa.txt");
  Params.put (File1.getname (), file1);
  
  GetView ();
  Httputil.get (URL, params, new Filesendresponselistener (this, this, V, MAX_TV, Num_tv, ProgressBar));
 

The listening events here are simply pasted ... The Listener event passes the control ... is to better show the user ... Here, a progress bar is set up to run through the entire request-response process ... If you download or upload too many files and resources ... We are required to notify the user of the relevant progress. Can't always die in the interface. So the user can not know whether or not to complete the data upload or download ...

Package com.example.andbasehttp;
Import Android.app.AlertDialog;
Import Android.content.Context;
Import Android.view.View;
Import Android.widget.TextView;
Import com.ab.activity.AbActivity;
Import Com.ab.http.AbStringHttpResponseListener;

Import Com.ab.view.progress.AbHorizontalProgressBar;
 public class Filesendresponselistener extends abstringhttpresponselistener{private int max=100;
 private int progress=0;
 Private abactivity activity;
 private context;
 Private Alertdialog Dialog;
 Private view view;
 Private TextView Max_tv,num_tv;
 
 Private Abhorizontalprogressbar ProgressBar; Public Filesendresponselistener (abactivity activity,context context,view V,textview V1,textview,
  Abhorizontalprogressbar ProgressBar) {this.activity=activity;
  This.context=context;
  This.view=v;
  THIS.MAX_TV=V1;
  This.num_tv=v2;
 This.progressbar=progressbar;
  @Override public void onsuccess (int statusCode, String content) {activity.showtoast ("onsuccess"); System.out.prINTLN (content); @Override public void onfailure (int statusCode, String content,throwable error) {Activity.showtoast (error.tostring
 ());
  @Override public void OnStart () {Max_tv.settext (progress+ "/" +string.valueof (max));
  Progressbar.setmax (max);
  Progressbar.setprogress (progress);
  Activity.showtoast ("Downloading");
 Dialog=activity.showdialog ("Downloading", view); @Override public void onprogress (int byteswritten, int totalsize) {Max_tv.settext (byteswritten/(Totalsize/max) + "/"
  +max);
 Progressbar.setprogress (byteswritten/(Totalsize/max));
  @Override public void OnFinish () {dialog.cancel ();
 Dialog=null;

 }
}

The classes involved are all classes in the Com.ab.http warranty ...
1.abstringhttpresponselistener.java

2.abbinaryhttpresponselistener.java

3.abfilehttpresponselistener.java

These three classes are an inheritance of the Abhttpresponselistener.java ... Inherited some of the relevant methods within it. Include request start, end, failure, etc. function ...

Abhttpclient.java is used to complete the request-the implementation of the connection process ... It also contains the encapsulation of the data;

Abhttputils.java is a middle layer of the method call to Post,get;

Abrequestparams.java is a class of request parameter processing, which includes not only the processing of request parameters, but also the process of creating the entity and adding relevant parameters to the entity.

The above is the entire content of this article, I hope to help you learn.

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.