前面經過.net Webapi搭建了數據訪問及處理平臺,如下介紹如何經過Android來訪問Webapi的數據。git
Android的經常使用的網絡訪問方式是使用HttpClient和HttpURLConnection、OKHttp等,其中OKHttp很是高效,支持SPDY、鏈接池、GZIP和 HTTP 緩存。默認狀況下,OKHttp會自動處理常見的網絡問題,像二次鏈接、SSL的握手問題。而咱們如今搭建的webapi主要使用REST的架構風格,Square提供的開源產品Retrofit,爲Android平臺的應用提供一個類型安全的REST客戶端。github
Retroft基於註解,能夠把結構化的數據轉化爲Java實體類。web
咱們採用gson解析JSON數據,默認狀況下解析必須名稱大小寫一致,高級應用能夠參考Gson 解析教程。api
首先咱們定義一個實體類緩存
/** * BearerToken實體類 */ public class BearerToken { private String access_token; private String token_type; private Integer expires_in; private String userName; private Date issued; private Date expires; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getToken_type() { return token_type; } public void setToken_type(String token_type) { this.token_type = token_type; } public Integer getExpires_in() { return expires_in; } public void setExpires_in(Integer expires_in) { this.expires_in = expires_in; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Date getIssued() { return issued; } public void setIssued(Date issued) { this.issued = issued; } public Date getExpires() { return expires; } public void setExpires(Date expires) { this.expires = expires; } }
使用Retrofit註解方式定義獲取token的服務安全
/** * 認證服務 */ public interface AuthenticationService { //獲取Token @POST Call<BearerToken> getToken(@Field("grant_type") String grantType, @Field("username") String userName, @Field("password") String password); }
編寫單元測試網絡
@Test public void TestGetToken() throws Exception{ Retrofit retrofit=new Retrofit.Builder() .baseUrl("http://localhost:2616/") .addConverterFactory(GsonConverterFactory.create()) .build(); AuthenticationService service=retrofit.create(AuthenticationService.class); Call<BearerToken> call=service.getToken("password","夢秋@com","123456"); BearerToken token=call.execute().body(); }
運行測試,獲取到token的數據,如圖: 架構
搞定認證後,下面再來看看怎麼經過token獲取數據。單元測試
再定義一個用戶信息的實體類測試
/** * 用戶信息 */ public class UserInfo { //用戶名稱 private String Name; public String getName() { return Name; } public void setName(String name) { Name = name; } }
使用Retrofit基於註解的方式定義獲取用戶信息的接口
/** * 用戶處理服務 */ public interface UserService { @GET("api/User") Call<UserInfo> getUserInfo(@Header("Authorization") String accessToken); }
編寫單元測試
public void TestGetUserInfo() throws Exception { Retrofit retrofit=new Retrofit.Builder() .baseUrl("http://localhost:2616/") .addConverterFactory(GsonConverterFactory.create()) .build(); UserLoginService service=retrofit.create(UserLoginService.class); String token=getToken(); Call<UserInfo> userInfos= service.getUserInfo(token); UserInfo info=userInfos.execute().body();
Assert.assertNotNull(info);
Assert.assertNotNull(info.getName());
}