Introduction to Android network request library ES1en ES2en ES3en

  • 2020-06-23 01:56:39
  • OfStack

Android Network Request Library: ES2en-ES3en-ES4en Open source framework
The previous article described how the client requests the server - Post requests. Today I introduce the android-ES8en-ES9en library, an open source library for a request server.
1. The concept:
This network request library is an asynchronous network request processing library based on Apache HttpClient library. The network processing is all based on non-ES15en threads of Android, and the request results are processed through callback method (anonymous inner class).
2. Features:
(1). Processing asynchronous Http requests and processing callback results through anonymous inner classes
**(2).**Http asynchronous requests are located in non-UI threads and do not block UI operations.
(3). Upload and download concurrent request processing files through thread pool, and the response results are automatically packaged in JSON format.
3. Introduction of corresponding core classes:
(1).AsyncHttpResponseHandler: Request returns the class that handles custom messages such as success, failure, start, finish, etc.
(2).BinaryHttpResponseHandler: subclass of AsyncHttpResponseHandler. This class is a byte stream return processing class. Used for processing pictures, etc.
(3).JsonHttpResponseHandler: subclass of AsyncHttpResponseHandler. This is a class used when communicating with Json data between a server and a client. The client requests the server for parameters of the Json data type, and the server returns to the client for data of the Json data type.
(4).RequestParams: Class that encapsulates parameter processing. Encapsulate the parameters requested by the client in this class.
(5).AsyncHttpClient: Class requested by the asynchronous client.
(6).SyncHttpClient: Class for synchronizing client requests. Subclasses of AsyncHttpClient.
Note: HttpUtil is a class that lists the get methods that we usually use, and calls the class where you want to use it. The ES47en-ES48en-ES49en-1.4.7..ES50en file package needs to be added.
The code is as follows:

(1).AsyncJsonUtilGet.java


package com.chengdong.su.util.get;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 *  Asynchronous request server 
 * 
 * @author scd
 * 
 */
public class AsyncJsonUtilGet {
  private static final String URL = "";
  private Context mContext;

  /**
   *  A constructor 
   * 
   * @param mContext
   */
  public AsyncJsonUtilGet(Context mContext) {
    super();
    this.mContext = mContext;
  }

  /**
   *  Registered mail 
   */
  public void emailRegister(String email, String password, String username) {

    RequestParams params = new RequestParams();
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("email", email);
      jsonObject.put("password", password);
      jsonObject.put("username", username);

    } catch (JSONException e) {
      e.printStackTrace();
    }
    params.put("jsonObject", jsonObject);
    // get Request way 
    HttpUtil.get(URL, params, new JsonHttpResponseHandler() {

      @Override
      public void onFailure(int statusCode, Header[] headers,
          Throwable throwable, JSONObject errorResponse) {
        super.onFailure(statusCode, headers, throwable, errorResponse);
        Toast.makeText(mContext, "Register failed!", Toast.LENGTH_SHORT)
            .show();
      }

      @Override
      public void onSuccess(int statusCode, Header[] headers,
          JSONObject response) {
        String errorCode = response.optString("ErrorCode");
        //  Indicates that the request was successful 
        if (errorCode.equals("0")) {
          Toast.makeText(mContext, " Registered successfully ", Toast.LENGTH_LONG).show();
          // response : The returned data is in this parameter, and the function is implemented according to the business requirements 
        } else {
          super.onSuccess(statusCode, headers, response);
        }
      }

    });

  }

}

(2). HttpUtil. java tool class: Note: jar package needs to be added


package com.chengdong.su.util.get;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class HttpUtil {
  public static final String STATUS_NETWORK = "network_available";
  private static AsyncHttpClient client = new AsyncHttpClient();

  static {
    client.setTimeout(11000);
  }

  public static void get(String urlString, AsyncHttpResponseHandler res) {
    client.get(urlString, res);
  }

  public static void get(String urlString, RequestParams params,
      AsyncHttpResponseHandler res) {
    client.get(urlString, params, res);
  }

  public static void get(String urlString, JsonHttpResponseHandler res)

  {
    client.get(urlString, res);
  }

  public static void get(String urlString, RequestParams params,
      JsonHttpResponseHandler res)

  {
    client.get(urlString, params, res);
  }

  public static void get(String uString, BinaryHttpResponseHandler bHandler)

  {
    client.get(uString, bHandler);
  }

  public static AsyncHttpClient getClient() {
    return client;
  }

  public static boolean isNetworkConnected(Context context) {
    if (context != null) {
      ConnectivityManager mConnectivityManager = (ConnectivityManager) context
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo mNetworkInfo = mConnectivityManager
          .getActiveNetworkInfo();
      if (mNetworkInfo != null) {
        return mNetworkInfo.isAvailable();
      }
    }
    return false;
  }

  //  from UrlConnection Gets the file name 
  public static String getFileName(String url) {
    String fileName = null;
    boolean isOK = false;
    try {
      URL myURL = new URL(url);

      URLConnection conn = myURL.openConnection();
      if (conn == null) {
        return null;
      }
      Map<String, List<String>> hf = conn.getHeaderFields();
      if (hf == null) {
        return null;
      }
      Set<String> key = hf.keySet();
      if (key == null) {
        return null;
      }

      for (String skey : key) {
        List<String> values = hf.get(skey);
        for (String value : values) {
          String result;
          try {
            result = value;
            int location = result.indexOf("filename");

            if (location >= 0) {
              result = result.substring(location
                  + "filename".length());
              result = java.net.URLDecoder
                  .decode(result, "utf-8");
              result = result.substring(result.indexOf("\"") + 1,
                  result.lastIndexOf("\""));

              fileName = result
                  .substring(result.indexOf("=") + 1);
              isOK = true;
            }
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }
        }
        if (isOK) {
          break;
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return fileName;
  }

}

The home of the open source is introduced: http: / / open ofstack. com project/app - framework/android - async - http. html


Related articles: