当前位置: 移动技术网 > 移动技术>移动开发>Android > Android详解之NoHttp最基本使用(无封装)

Android详解之NoHttp最基本使用(无封装)

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

nohttp是专门做android网络请求与下载的框架,nohttp基本使用方法如下

本文demo源码下载地址:

本文的例子来自上面的demo中的originalactivity中。

代码

对于新手, 看别人封装好的代码允许要稍微吃力一点,尤其是一个框架,所以我们先看nohttp最原始的使用方法:

public class originalactivity extends baseactivity implements view.onclicklistener {

 /**
  * 用来标志请求的what, 类似handler的what一样,这里用来区分请求
  */
 private static final int nohttp_what_test = 0x001;

 /**
  * 请求的时候等待框
  */
 private waitdialog mwaitdialog;

 /**
  * 请求队列
  */
 private requestqueue requestqueue;

 @override
 protected void onactivitycreate(bundle savedinstancestate) {
  settitle(application.getinstance().nohttptitlelist[0]);
  setcontentview(r.layout.activity_original);
  // 按钮点击监听
  findview(r.id.btn_start).setonclicklistener(this);

  mwaitdialog = new waitdialog(this);

  // 创建请求队列, 默认并发3个请求, 传入数字改变并发数量: nohttp.newrequestqueue(1);
  requestqueue = nohttp.newrequestqueue();
 }

 @override
 public void onclick(view v) {
  // 创建请求对象
  request<string> request = nohttp.createstringrequest(url, requestmethod.post);

  // 添加请求参数
  request.add("username", "yolanda");
  request.add("userpass", 1);
  request.add("userage", 1.25);

  // 上传文件
  request.add("userhead", new filebinary(new file(path)));

  // 添加请求头
  request.addheader("author", "nohttp_sample");

  // 设置一个tag, 在请求完(失败/成功)时原封不动返回; 多数情况下不需要
  // request.settag(object);

  /*
   * what: 当多个请求同时使用同一个onresponselistener时用来区分请求, 类似handler的what一样
   * request: 请求对象
   * onresponselistener 回调对象,接受请求结果
   */
  requestqueue.add(nohttp_what_test, request, onresponselistener);
 }

 /**
  * 回调对象,接受请求结果
  */
 private onresponselistener<string> onresponselistener = new onresponselistener<string>() {
  @suppresswarnings("unused")
  @override
  public void onsucceed(int what, response<string> response) {
   if (what == nohttp_what_test) {// 判断what是否是刚才指定的请求
    // 请求成功
    string result = response.get();// 响应结果
    // 响应头
    headers headers = response.getheaders();
    headers.getresponsecode();// 响应码
    response.getnetworkmillis();// 请求花费的时间
   }
  }

  @override
  public void onstart(int what) {
   // 请求开始,显示dialog
   mwaitdialog.show();
  }

  @override
  public void onfinish(int what) {
   // 请求结束,关闭dialog
   mwaitdialog.dismiss();
  }

  @override
  public void onfailed(int what, string url, object tag, charsequence error, int rescode, long ms) {
   // 请求失败
   ...
  }
 };

 @override
 protected void ondestroy() {
  super.ondestroy();
  requestqueue.cancelall();// 退出app时停止所有请求
  requestqueue.stop();// 退出app时停止队列
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

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

相关文章:

验证码:
移动技术网