标签:android 网络 robospice pojo request
RoboSpice是一个使你建立异步的长时间的运行任务异常轻松的一个网络库,在网络请求,缓存支持,和提供开箱即用的rest请求方面尤为强大
特性如下
github地址 https://github.com/stephanenicolas/robospice
下面我们来使用这个库,使用它有几个步骤
在书写代码前,我们先在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 ,简单重写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继承它
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());
}
}
根据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();
}
});
}
在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
标签:android 网络 robospice pojo request
原文地址:http://blog.csdn.net/sbsujjbcy/article/details/45070711