欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android网络请求库android-async-http介绍

程序员文章站 2023-02-02 11:31:02
android网络请求库:android-async-http开源框架 之前有一篇描述了客户端请求服务器端的方式—post的请求方式。今天介绍一个请求服务器的一个开源库...

android网络请求库:android-async-http开源框架
之前有一篇描述了客户端请求服务器端的方式—post的请求方式。今天介绍一个请求服务器的一个开源库—android-async-http库。
1. 概念:
这个网络请求库是基于apache httpclient库之上的一个异步网络请求处理库,网络处理均基于android的非ui线程,通过回调方法(匿名内部类)处理请求结果。
2. 特征:
(1).处理异步http请求,并通过匿名内部类处理回调结果
**(2).**http异步请求均位于非ui线程,不会阻塞ui操作。
(3).通过线程池处理并发请求处理文件上传、下载,响应结果自动打包json格式。
3. 相应的核心类的介绍:
(1).asynchttpresponsehandler:请求返回处理成功、失败、开始、完成等自定义的消息的类。
(2).binaryhttpresponsehandler:asynchttpresponsehandler的子类。该类是一个字节流返回处理的类。用于处理图片等。
(3).jsonhttpresponsehandler:asynchttpresponsehandler的子类。这是一个服务器与客户端之间用json数据交流时使用的类。客户端请求服务器的参数是json数据类型的,服务器返回给客户端的数据也是json数据类型的。
(4).requestparams:封装参数处理的类。将客户端请求的参数封装在该类中。
(5).asynchttpclient:异步客户端请求的类。
(6).synchttpclient:同步客户端请求的类。asynchttpclient的子类。
注意:httputil这个类主要列出了我们常用的get方法,在要使用的地方,调用该类就行了。需要添加android-async-http-1.4.7.jar文件包。
代码如下:

(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;

/**
 * 异步请求服务器
 * 
 * @author scd
 * 
 */
public class asyncjsonutilget {
  private static final string url = "";
  private context mcontext;

  /**
   * 构造方法
   * 
   * @param mcontext
   */
  public asyncjsonutilget(context mcontext) {
    super();
    this.mcontext = mcontext;
  }

  /**
   * 邮箱注册
   */
  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请求方式
    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");
        // 表示请求成功
        if (errorcode.equals("0")) {
          toast.maketext(mcontext, "注册成功", toast.length_long).show();
          // response:返回的数据都在这个参数中,根据业务要求进行实现功能
        } else {
          super.onsuccess(statuscode, headers, response);
        }
      }

    });

  }

}

(2).httputil.java工具类:注:需要添加jar包

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;
  }

  // 从urlconnection中获取文件名称
  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;
  }

}

开源之家介绍: