標籤:android 網路 robospice pojo request
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
RoboSpice:android非同步網路程式庫簡單用法