当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发中使用Volley库发送HTTP请求的实例教程

Android开发中使用Volley库发送HTTP请求的实例教程

2019年07月24日  | 移动技术网移动技术  | 我要评论

android volley 是google开发的一个网络lib,可以让你更加简单并且快速的访问网络数据。volley库的网络请求都是异步的,你不必担心异步处理问题。
volley的优点:

  • 请求队列和请求优先级
  • 请求cache和内存管理
  • 扩展性性强
  • 可以取消请求

下载和编译volley.jar
需要安装git,ant,android sdk
clone代码:

git clone https://android.googlesource.com/platform/frameworks/volley

编译jar:

android update project -p . ant jar

添加volley.jar到你的项目中
不过已经有人将volley的代码放到github上了:
https://github.com/mcxiaoke/android-volley,你可以使用更加简单的方式来使用volley:
maven
format: jar

<dependency>
  <groupid>com.mcxiaoke.volley</groupid>
  <artifactid>library</artifactid>
  <version>1.0.6</version>
</dependency>

gradle
format: jar

compile 'com.mcxiaoke.volley:library:1.0.6'

volley工作原理图

201656151349558.jpg (1428×802)

创建volley 单例
使用volley时,必须要创建一个请求队列requestqueue,使用请求队列的最佳方式就是将它做成一个单例,整个app使用这么一个请求队列。

public class appcontroller extends application {

public static final string tag = appcontroller.class
    .getsimplename();

private requestqueue mrequestqueue;
private imageloader mimageloader;

private static appcontroller minstance;

@override
public void oncreate() {
  super.oncreate();
  minstance = this;
}

public static synchronized appcontroller getinstance() {
  return minstance;
}

public requestqueue getrequestqueue() {
  if (mrequestqueue == null) {
    mrequestqueue = volley.newrequestqueue(getapplicationcontext());
  }

  return mrequestqueue;
}

public imageloader getimageloader() {
  getrequestqueue();
  if (mimageloader == null) {
    mimageloader = new imageloader(this.mrequestqueue,
        new lrubitmapcache());
  }
  return this.mimageloader;
}

public <t> void addtorequestqueue(request<t> req, string tag) {
  // set the default tag if tag is empty
  req.settag(textutils.isempty(tag) ? tag : tag);
  getrequestqueue().add(req);
}

public <t> void addtorequestqueue(request<t> req) {
  req.settag(tag);
  getrequestqueue().add(req);
}

public void cancelpendingrequests(object tag) {
  if (mrequestqueue != null) {
    mrequestqueue.cancelall(tag);
  }
}
}

另外,你还需要一个cache来存放请求的图片:

public class lrubitmapcache extends lrucache<string, bitmap> implement imagecache {
  public static int getdefaultlrucachesize() {
    final int maxmemory = (int) (runtime.getruntime().maxmemory() / 1024);
    final int cachesize = maxmemory / 8;

    return cachesize;
  }

  public lrubitmapcache() {
    this(getdefaultlrucachesize());
  }

  public lrubitmapcache(int sizeinkilobytes) {
    super(sizeinkilobytes);
  }

  @override
  protected int sizeof(string key, bitmap value) {
    return value.getrowbytes() * value.getheight() / 1024;
  }

  @override
  public bitmap getbitmap(string url) {
    return get(url);
  }

  @override
  public void putbitmap(string url, bitmap bitmap) {
    put(url, bitmap);
  }
}

别忘记在androidmanifest.xml文件中添加android.permission.internet权限。

http请求实例

  private context mcontext;
  private requestqueue mrequestqueue;
  private stringrequest mstringrequest;

  // 利用volley实现post请求
  private void volley_post() {
    string url = "http://aplesson.com/wap/api/user.php?action=login";
    mcontext = this;
    mrequestqueue = volley.newrequestqueue(mcontext);
    mstringrequest = new stringrequest(method.post, url,
        new response.listener<string>() {
          @override
          public void onresponse(string response) {
            system.out.println("请求结果:" + response);
          }
        }, new response.errorlistener() {
          @override
          public void onerrorresponse(volleyerror error) {
            system.out.println("请求错误:" + error.tostring());
          }
        }) {
      // 携带参数
      @override
      protected hashmap<string, string> getparams()
          throws authfailureerror {
        hashmap<string, string> hashmap = new hashmap<string, string>();
        hashmap.put("un", "852041173");
        hashmap.put("pw", "852041173abc");
        return hashmap;
      }

      // volley请求类提供了一个 getheaders()的方法,重载这个方法可以自定义http 的头信息。(也可不实现)
      public map<string, string> getheaders() throws authfailureerror {
        hashmap<string, string> headers = new hashmap<string, string>();
        headers.put("accept", "application/json");
        headers.put("content-type", "application/json; charset=utf-8");
        return headers;
      }

    };

    mrequestqueue.add(mstringrequest);

  }

  private jsonobjectrequest mjsonobjectrequest;

  // 利用volley实现json数据请求
  private void volley_json() {
    mcontext = this;
    string url = "http://aplesson.com/data/101010100.html";
    // 1 创建requestqueue对象
    mrequestqueue = volley.newrequestqueue(mcontext);
    // 2 创建jsonobjectrequest对象
    mjsonobjectrequest = new jsonobjectrequest(url, null,
        new response.listener<jsonobject>() {
          @override
          public void onresponse(jsonobject response) {
            system.out.println("请求结果:" + response.tostring());
          }
        }, new response.errorlistener() {
          @override
          public void onerrorresponse(volleyerror error) {
            system.out.println("请求错误:" + error.tostring());
          }
        });

    // 3 将jsonobjectrequest添加到requestqueue
    mrequestqueue.add(mjsonobjectrequest);

  }

  // 利用volley实现get请求
  private void volley_get() {
    mcontext = this;
    string url = "http://www.aplesson.com/";
    // 1 创建requestqueue对象
    mrequestqueue = volley.newrequestqueue(mcontext);
    // 2 创建stringrequest对象
    mstringrequest = new stringrequest(url,
        new response.listener<string>() {
          @override
          public void onresponse(string response) {
            system.out.println("请求结果:" + response);
          }
        }, new response.errorlistener() {
          @override
          public void onerrorresponse(volleyerror error) {
            system.out.println("请求错误:" + error.tostring());
          }
        });
    // 3 将stringrequest添加到requestqueue
    mrequestqueue.add(mstringrequest);
  }


volley提供了jsonobjectrequest、jsonarrayrequest、stringrequest等request形式。jsonobjectrequest:返回json对象。
jsonarrayrequest:返回jsonarray。
stringrequest:返回string,这样可以自己处理数据,更加灵活。
另外可以继承request<t>自定义request。

取消request
activity里面启动了网络请求,而在这个网络请求还没返回结果的时候,activity被结束了,此时如果继续使用其中的context等,除了无辜的浪费cpu,电池,网络等资源,有可能还会导致程序crash,所以,我们需要处理这种一场情况。使用volley的话,我们可以在activity停止的时候,同时取消所有或部分未完成的网络请求。volley里所有的请求结果会返回给主进程,如果在主进程里取消了某些请求,则这些请求将不会被返回给主线程。volley支持多种request取消方式。
可以针对某些个request做取消操作:

 @override
  public void onstop() {
    for (request <?> req : mrequestqueue) {
      req.cancel();
    }
  }

取消这个队列里的所有请求:

 @override
  protected void onstop() {
    // todo auto-generated method stub
    super.onstop();
    mrequestqueue.cancelall(this);
  }

可以根据requestfilter或者tag来终止某些请求

 @override
  protected void onstop() {
    // todo auto-generated method stub
    super.onstop();

    mrequestqueue.cancelall( new requestfilter() {});
    or
    mrequestqueue.cancelall(new object());
  }

volley支持http的get、post、put、delete等方法。


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网