1.添加依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' //Retrofit2所需要的包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' //ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4' //ConverterFactory的String依赖包
2.使用到的API public class Api {
public static final String HOST = "http://gank.io/api/" ;
public static final String URL = "data/Android/10/1" ;
public static final String HOSTURL = "http://120.27.23.105/user/login" ;
}
3.创建ServerApi public interface ServerApi {
@GET (Api.URL )
Call<Bean> bean();
@POST (Api.HOSTURL )
Call<LoginBean> login(@Query ("mobile" )String mobile,@Query ("password" )String pwd);
}
4.创建RetrofitHelper类 public class RetrofitHelper {
public static OkHttpClient client ;
public static ServerApi serverApi ;
static {
getOkHttp ();
}
public static OkHttpClient getOkHttp() {
if (client == null ){
synchronized (RetrofitHelper.class ){
if (client == null ){
client = new OkHttpClient();
}
}
}
return client ;
}
public static ServerApi getServerApi(){
if (serverApi == null ){
synchronized (ServerApi.class ){
if (serverApi == null ){
serverApi = OnCreatApi (ServerApi.class , Api.HOST );
}
}
}
return serverApi ;
}
public static <T > T OnCreatApi(Class<T > tClass,String url){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create ())
.build();
return retrofit.create(tClass);
}
}
6.在MainActivity中的逻辑 public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
ServerApi serverApi = RetrofitHelper.getServerApi ();
Call<Bean> beanCall = serverApi.bean();
beanCall.enqueue(new Callback<Bean>() {
@Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
Bean bean = response.body();
Log.e ("TAG" ,bean.getResults().get(0 ).toString());
}
@Override
public void onFailure(Call<Bean> call, Throwable t) {
}
});
Call<LoginBean> loginBeanCall = serverApi.login("13833887755" ,"123456" );
loginBeanCall.enqueue(new Callback<LoginBean>() {
@Override
public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
LoginBean login = response.body();
Log.e ("TAG" ,login.getMsg());
}
@Override
public void onFailure(Call<LoginBean> call, Throwable t) {
}
});
}
}