1. 程式人生 > >Android Retrofit (不咋會待補全)(比較麻煩 慎用)

Android Retrofit (不咋會待補全)(比較麻煩 慎用)

首先是聯網許可權和倒入依賴

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();
            }
        } );
    }
}