目录: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'