目錄:andorid jar/庫源碼解析 html
經過封裝okhttp庫,來進行web通信,而且使用動態代理的方式,來調用接口地址,經過回調賦值結果。java
定義一個接口,用於訪問使用。git
public interface IServiceApi { @FormUrlEncoded @POST("login") Call<LoginResult> login(@Field("name") String name, @Field("pwd") String pwd); @GET("getinfo") Call<UserInfo> getinfo(@Query("token") String token); @GET("getinfo2") Call<UserInfo> getinfo2(@Query("token") String token); }
調用接口1.能夠在main中調用,由於是經過異步執行(enqueue)github
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl("http://192.168.86.11:8087/").build(); IServiceApi api = retrofit.create(IServiceApi.class); Call<LoginResult> call = api.login("test", "test1234"); call.enqueue(new Callback<LoginResult>() { @Override public void onResponse(Call<LoginResult> call, Response<LoginResult> response) { LoginResult loginResult = response.body(); if(loginResult != null) { } } @Override public void onFailure(Call<LoginResult> call, Throwable t) { Log.i(tag, "ex " + t.getMessage()); } });
調用接口2.能夠在main中調用,由於是經過異步執行(enqueue)web
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl("http://192.168.86.11:8087/").build(); IServiceApi api = retrofit.create(IServiceApi.class); Call<UserInfo> call = api.getinfo("testtesttest"); call.enqueue(new Callback<UserInfo>() { @Override public void onResponse(Call<UserInfo> call, Response<UserInfo> response) { UserInfo userInfo = response.body(); if(userInfo != null) { } } @Override public void onFailure(Call<UserInfo> call, Throwable t) { Log.i(tag, "ex " + t.getMessage()); } });
同步調用接口3.api
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl("http://192.168.86.11:8087/").build(); IServiceApi api = retrofit.create(IServiceApi.class); Call<LoginResult> call = api.login("test", "test1234"); try { Response<LoginResult> resultResponse = call.execute(); LoginResult result = resultResponse.body(); }catch (Exception e){ e.printStackTrace(); }
A:異步調用異步
一、建立一個Retrofit對象。ide
二、retrofit.create(IServiceApi.class); // 使用Proxy.newProxyInstance 建立一個接口的代理對象。內部使用 ServiceMethod配合OkHttpCall調用,構造他們須要的對象數據ui
三、調用enqueue,內部構造okhttp3.Call對象,執行對象的enqueue方法。而後在okhttp3$Callback方法中,調用retrofit2的 回調,賦值成功和失敗。google
B:同步調用
一、同理,同步調用,最後也是調用的。okhtt3.Call的execute方法。
源碼:https://github.com/square/retrofit
implementation 'com.squareup.retrofit2:retrofit:2.0.2'implementation 'com.squareup.retrofit2:converter-gson:2.0.2'implementation 'com.google.code.gson:gson:2.8.5'implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.2'