首先是联网权限和倒入依赖
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
<uses-permission android:name="android.permission.INTERNET"/>
首先定义一个借口
package soexample.umeng.com.day04retrofit; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface DataService { @GET("/ad/getAd") Call<ResponseBody> getBanner(); @GET("/product/getCarts") Call<ResponseBody> getBanners(@Query( "uid" )int id); }
定义Retrofit工具类
package soexample.umeng.com.day04retrofit; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; public class RetrofitUtils { private Retrofit mRetrofit; RetrofitUtils() { } private static RetrofitUtils mRetrofitUtils; public static RetrofitUtils getmRetrofitUtils() { if (mRetrofitUtils == null) { mRetrofitUtils = new RetrofitUtils(); } return mRetrofitUtils; } public void init() { mRetrofit = new Retrofit.Builder() .baseUrl( "http://www.zhaoapi.cn" ) .build(); } public void getBanner() { mRetrofit.create( DataService.class ).getBanners( 71 ).enqueue( new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { try { String string = response.body().string(); Log.i("TAG","MSG"+string); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } } ); } }
在MainActivity布局文件里定义一个按钮 用来使用工具类
采用了单例模式 所以要初始化
package soexample.umeng.com.day04retrofit; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import retrofit2.Retrofit; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_main ); RetrofitUtils.getmRetrofitUtils().init(); findViewById( R.id.look ).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { RetrofitUtils.getmRetrofitUtils().getBanner(); } } ); } }