The Android AndBase framework uses encapsulated functions to complete Http requests (3)

  • 2021-06-28 14:09:58
  • OfStack

This is the third note for AndBase framework learning. Friends who want to know AndBase framework can read this article and learn from it together.

Learning content:

1. Use the AndBase framework to implement Http Get requests without parameters...

2. Use the AndBase framework to implement Http Post requests...

3. Use the AndBase framework to implement Http Get requests...

The AndBase framework provides us with a number of related methods for completing Http network requests... Overall, it is an encapsulation of Http requests, but I personally think that this module of network requests is more recommended to use the Volley framework... The building master compares the source code in the two frameworks... Volley uses more abstract methods to encapsulate in the interface.Then expose the interface to the outside world. Other classes need to implement internal abstract methods while implementing the interface... while AndBase uses inheritance..Inheritance of parent class..Implementation class overrides the encapsulated methods by override to proceed to the next step...

The writing of Volley source code is better than the source code of the two network requests. Volley was launched by Google, and it is only for the network requests module. AndBase is also very excellent, it is a heavyweight framework written by domestic cattle people, the modules involved are very broad, or very useful...

1. Implement Http Get request without parameters using the AndBase framework

1 Normal network requests can use Get mode to complete network requests if they do not involve changes in data information, that is, no security issues. Get requests are also divided into parametric and non-parametric, which gives me the feeling that 1 can be used to upload resource data to the server... First, introduce 1 non-parametric Get requests.. Or first, see from the source code...

The source code is called first by using the AbHttpUtils.get() function (), but it doesn't matter (... go inside the AbHttpClient class by this method (... execute the following source code (... with or without arguments). This method is called.. Passing null with or without arguments is OK with the second argument (...)


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 Message through Handler... and opens a thread pool to submit the current request. Finally, the doGet () method is executed, while Handler1 processes responseListener messages. The source code process for the doGet () method is as follows


private void doGet(String url,AbRequestParams params,AbHttpResponseListener responseListener){
   try {
    
    responseListener.sendStartMessage();
    
    if(!debug && !AbAppUtil.isNetworkAvailable(mContext)){
     responseListener.sendFailureMessage(AbConstant.CONNECT_FAILURE_CODE,AbConstant.CONNECTEXCEPTION, new AbAppException(AbConstant.CONNECTEXCEPTION));
     return;
    }
    
    //HttpGet Connecting Objects  
    if(params!=null){
     url += params.getParamString(); // If there is a reference , Then get the relevant parameters ...
    }
    HttpGet httpRequest = new HttpGet(url); // Define Connection Objects ..
    
    BasicHttpParams httpParams = new BasicHttpParams();
    
    //  Timeout for taking connections from the connection pool, set to 1 second 
    ConnManagerParams.setTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    //  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 Parameters 
    httpRequest.setParams(httpParams);
    
    // Obtain HttpClient object  
    HttpClient httpClient = new DefaultHttpClient(); 
    // request HttpClient , get HttpResponse 
    HttpResponse httpResponse = httpClient.execute(httpRequest); 
    // Request succeeded  
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    
    // Get the returned string  
    HttpEntity mHttpEntity = httpResponse.getEntity();
    if (statusCode == HttpStatus.SC_OK){ 
     if(responseListener instanceof AbStringHttpResponseListener){
      String content = EntityUtils.toString(mHttpEntity);
      ((AbStringHttpResponseListener)responseListener).sendSuccessMessage(statusCode, content);
     }else if(responseListener instanceof AbBinaryHttpResponseListener){
      readResponseData(mHttpEntity,((AbBinaryHttpResponseListener)responseListener));
     }else if(responseListener instanceof AbFileHttpResponseListener){
      // Get File Name 
      String fileName = AbFileUtil.getFileNameFromUrl(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 call procedure is actually very clear..

Whether the doGet () method or the doPost () method mode is basically the same, it is necessary to establish a connection object first, HttpGet or HttpPost. The difference is that Get requests with parameters directly add params after url.Post requests need to get entity data..Include the params we passed in the entity data..Set up parameters related to the connection process and data reading process, such as timeout, Http version used, UserAgent set, etc..After setting up, execute the request to get response...

There is a process of judging the type of response data that is returned, whether it is a basic String type, an Byte type related to pictures or videos, or an File type related to files.All encapsulate entity data...call sendSuccessMessage after encapsulation and Handler automatically goes back to process Message...call OnSuccess method at last..Return data to client..

Or look at the actual calling process:

Get request dispatch without parameters, where appropriate monitoring needs to be set:


public void FileClick(View v){
 url="http://192.168.199.172:8080/JSP/imageview.jpg";
 getView();
 httpUtil.get(url, new FileResponseListener(this, this, v,max_tv,num_tv,progressBar));
}
 GetResponseListener.java

An override of the monitoring of the response...A network request can be completed by setting url+related monitoring on the request and processing the requested data...Here, a download of the picture data is completed, and then the data is encapsulated into an Bitmap..So it can be displayed 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 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 v2, 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 results ", 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 Http Post request with AndBase framework

Actually, they are all called the same way, except the Post request needs to pass the relevant parameters.. Use the Post request with parameters.. Here is to pass the relevant parameters to an JSP to complete the validation 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));
}

I won't paste the PostResponseListener code here... Paste 1 the code for the JSP page... The relevant JSP code is as follows... The JSP code here is very simple... and I used it before when I used Volley... The JSP page is more complex than we can write on our own, so we can do more...


<%
 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. Use the AndBase framework to implement Http Get requests

Get request 1 with parameters is generally used for file, data upload.. Pass the uploaded resource and name as parameters to the server.. There are no security issues involved here.. So you can use Get request with parameters.. Upload files to the server here.. You need to add relevant 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));
 }

Here's a simple paste of listening events (... listening events pass controls.. to better show the user.. Here's a way to set a progress bar,To go through the whole request-response process...if there are too many files and resources to download or upload...we have to inform the user about the progress..There is no way to get stuck in the interface..So the user doesn't know if he has finished uploading or downloading the data...


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 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 v2, 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 within the com.ab.http guarantee...
1.AbStringHttpResponseListener.java

2.AbBinaryHttpResponseListener.java

3.AbFileHttpResponseListener.java

These three classes are an inheritance of AbHttpResponseListener.java... inherit one of its internal related methods... including functions such as request start, end, failure, etc..

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

AbHttpUtils.java is an intermediate layer that is invoked for post, get, etc.

AbRequestParams.java is a class of request parameter processing, which includes not only the processing of request parameters, but also the creation of entities, adding related parameters to entities, and so on.

This is the whole content of this article, and I hope it will be helpful for everyone to learn.


Related articles: