RoboSpice:android异步网络库简单用法

RoboSpice是一个使你建立异步的长时间的运行任务异常轻松的一个网络库,在网络请求,缓存支持,和提供开箱即用的rest请求方面尤为强大

特性如下

  • 支持 SDK版本8以上的版本
  • 异步执行网络请求(后台服务)
  • 支持开箱即用的rest(使用了 Spring Android or Google Http Client or Retrofit).)
  • 你的查询使用POJOs 作为参数,你会获得POJOs的请求结果
  • 可以以 Jackson or Jackson2 or Gson, or Xml,等格式缓存结果
  • 根据他们的生命周期通知活动或者任何上下文网络请求结果
  • 在UI线程中通知活动或者任何上下文
  • 像Android Loaders,而不像AsyncTasks,不存在内存泄露
  • 简单高容错的异常处理模型
  • 稳定高效
  • 支持请求取消,请求设置优先级,请求合并
  • 支持不同web服务的聚集
  • 大量的测试

github地址 https://github.com/stephanenicolas/robospice

下面我们来使用这个库,使用它有几个步骤

  • 使用一个预先设置好的SpiceService 或者自定义一个SpiceService ,这个SpiceService 会提供给所有请求使用。
  • 在Activity使用,这一步每个activity都不能少,你不得不去重复这一步。除非你在你的项目中使用了一个基类Activity,其他Activity继承了该基类
  • 创建一个SpiceRequest 和RequestListener,这两步也是不得不去为每一个请求重复书写代码。
  • 最后需要定义POJO 类来保存请求的结果

在书写代码前,我们先在android studio中新建一个项目,如果你使用的是eclipse,你需要将依赖包一个一个导入。
这里写图片描述

在android studio中,打开app下的buidl.gradle,加入以下依赖

    compile('com.octo.android.robospice:robospice-google-http-client:1.4.14') {
        exclude(group: 'org.apache.httpcomponents', module: 'httpclient')
    }
    compile('com.google.http-client:google-http-client-jackson2:1.19.0') {
        exclude(group: 'xpp3', module: 'xpp3')
        exclude(group: 'org.apache.httpcomponents', module: 'httpclient')
        exclude(group: 'junit', module: 'junit')
        exclude(group: 'com.google.android', module: 'android')
    }

然后再android{}中加入以下配置,否则会出现冲突包

 packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }

build一下就会将依赖包下载下来。

编写SpiceService

一切就绪后开始编写代码,这里我们使用自定义的SpiceService ,简单重写getThreadCount方法。

package cn.edu.zafu.robospicedemo.service;

/**
 * Created by lizhangqu on 2015/4/15.
 */
import com.octo.android.robospice.Jackson2GoogleHttpClientSpiceService;

public class HttpClientSpiceService extends Jackson2GoogleHttpClientSpiceService {

    @Override
    public int getThreadCount() {
        return 4;
    }

}

在manifest中声明这个service

 <service
      android:name=".service.HttpClientSpiceService"
      android:exported="false" />

编写SpiceRequest

由于所有的请求都要写一个SpiceRequest,所有我们先编写一个基类,其余的SpiceRequest继承它

package cn.edu.zafu.robospicedemo.webservice;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.octo.android.robospice.request.googlehttpclient.GoogleHttpClientSpiceRequest;

import java.io.IOException;
import java.util.HashMap;

public abstract class BaseGoogleHttpClientSpiceRequest<RESULT> extends GoogleHttpClientSpiceRequest<RESULT> {

    String url = null;
    HashMap<String, String > postParameters;

    protected BaseGoogleHttpClientSpiceRequest(Class<RESULT> clazz) {
        super(clazz);
    }

    public HttpRequest buildGetRequest(GenericUrl url) throws IOException {
        System.setProperty("http.keepAlive", "false");
        HttpRequest request = getHttpRequestFactory().buildGetRequest(url);
        request.getHeaders().setAcceptEncoding("gzip");
        request.getHeaders().set("Connection", "close");
        request.getHeaders().setAccept("text/html,application/xhtml+xml,application/xml,application/json");
        return request;
    }

    public HttpRequest buildPostRequest(GenericUrl url, HttpContent content) throws IOException {
        System.setProperty("http.keepAlive", "false");
        HttpRequest request = getHttpRequestFactory().buildPostRequest(url, content);
        request.getHeaders().setAcceptEncoding("gzip");
        request.getHeaders().set("Connection", "close");
        request.getHeaders().setAccept("text/html,application/xhtml+xml,application/xml,application/json");
        return request;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setPostParameters(HashMap<String, String> postParameters) {
        this.postParameters = postParameters;
    }
}

我们请求服务器上的一个json数据,其格式如下

{"id":1,"name":"zhangsan","age":20,"address":"china"}

我们编写一个PersonRequest

package cn.edu.zafu.robospicedemo.webservice;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.json.jackson2.JacksonFactory;

import cn.edu.zafu.robospicedemo.webservice.json.PersonJson;

/**
 * Created by lizhangqu on 2015/4/15.
 */
public class PersonRequest extends BaseGoogleHttpClientSpiceRequest<PersonJson> {

    public PersonRequest() {
        super(PersonJson.class);
    }

    @Override
    public PersonJson loadDataFromNetwork() throws Exception {

        HttpRequest request = null;
        GenericUrl genericUrl = new GenericUrl(url);

        if (postParameters == null) {
            request = getHttpRequestFactory().buildGetRequest(genericUrl);
        } else {
            HttpContent content = new UrlEncodedContent(postParameters);
            request = buildPostRequest(genericUrl, content);
        }
        request.setParser(new JacksonFactory().createJsonObjectParser());

        return request.execute().parseAs(getResultType());
    }

}

编写POJO

根据json格式编写

package cn.edu.zafu.robospicedemo.webservice.json;

import com.google.api.client.util.Key;

/**
 * Created by lizhangqu on 2015/4/15.
 */
public class PersonJson {
    @Key
    private int id;
    @Key
    private String name;
    @Key
    private int age;
    @Key
    private String address;
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


}

编写监听器

在MainActivity中编写一个函数

 public void requestTestData() {
        PersonRequest request = new PersonRequest();
        request.setUrl("http://121.199.33.93/7plus/index/hello");
        spiceManager.execute(request, new RequestListener<PersonJson>() {
            @Override
            public void onRequestFailure(SpiceException spiceException) {

            }

            @Override
            public void onRequestSuccess(PersonJson personJson) {
                Toast.makeText(getApplicationContext(),personJson.getId()+" "+personJson.getName()+" "+personJson.getAge()+" "+personJson.getAddress(),Toast.LENGTH_LONG).show();
            }
        });
    }

使用RoboSpice

在MainActivity中声明一个变量

  private SpiceManager spiceManager = new SpiceManager(HttpClientSpiceService.class);

重写生命周期

  @Override
    public void onStart() {
        spiceManager.start(this);
        super.onStart();
    }

    @Override
    public void onStop() {
        if (spiceManager.isStarted()) {
            spiceManager.shouldStop();
        }
        super.onStop();
    }

收尾工作

别忘记增加权限,在manifest中增加以下权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

运行

这时候运行一下,如果不出意外将有一个toast显示json数据中的内容

源码下载

基于android studio,下载链接
http://download.csdn.net/detail/sbsujjbcy/8599469

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值