Retrofit网络请求框架的简单使用


添加依赖

//retrofit
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

加权限

 
    
    
    
    

初始化retrofit

public class RetrofitUtil {

    public static RetrofitUtil retrofitUtil;
    public String url;
    private final Retrofit retrofit;

    //初始化retrofit
    public RetrofitUtil(String url) {
        this.url = url;
        //添加拦截器
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new RetrofitIntercepter()).build();
        retrofit = new Retrofit.Builder().baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(new Gson()))
//                .client(client)
                .build();
    }

    //拦截器     拦截器有点问题--
    class RetrofitIntercepter implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {

            Request request = chain.request();
            RequestBody body = request.body();
            if (body instanceof FormBody) {
                FormBody.Builder builder = new FormBody.Builder();
                for (int i = 0; i < ((FormBody) body).size(); i++) {
                    String key = ((FormBody) body).name(i);
                    String value = ((FormBody) body).value(i);
                    builder.add(key, value);
                }
                builder.add("source", "android");
                FormBody formBody = builder.build();
                Request request1 = request.newBuilder().post(formBody).build();
                Response response = chain.proceed(request1);
                return response;
            }

            return null;
        }
    }

    //通过反射实现子类
    public  T getUserData(Class clz) {
        T t = retrofit.create(clz);
        return t;
    }

    //单利模式
    public static RetrofitUtil getInstance(String u) {
        if (retrofitUtil == null) {
            retrofitUtil = new RetrofitUtil(u);
        }
        return retrofitUtil;
    }
    //


retrofit是通过注解的形式配置网络请求参数,所以创建接口  反射子类

public interface RetrofitService {
    //get请求  product/getProductDetail?source=android&pid=12
    @GET("product/getProductDetail")
    Call getList(@Query("pid") String pid);

    //get请求  product/getProductDetail?source=android&pid=12
    @POST("product/getProductDetail")
    Call getList_post(@Query("pid") String pid);
}

主方法    开始调用   retrofit

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button get;
    private Button post;
    private TextView tv;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化界面
        initView();

    }

    private void initView() {
        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);
        tv = (TextView) findViewById(R.id.tv);

        get.setOnClickListener(this);
        post.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.get:
                //初始化retrofit
                RetrofitUtil.getInstance(HttpConfig.baseUrl).getUserData(RetrofitService.class).getList("12").enqueue(new Callback() {
                    @Override
                    public void onResponse(Call call, Response response) {
                        Log.d(TAG, "onResponse: ===========" + response.body().getMsg());
                        tv.setText(response.body().getMsg());
                    }

                    @Override
                    public void onFailure(Call call, Throwable t) {

                    }
                });
                break;
            case R.id.post:
                RetrofitUtil.getInstance(HttpConfig.baseUrl).getUserData(RetrofitService.class).getList_post("12").enqueue(new Callback() {
                    @Override
                    public void onResponse(Call call, Response response) {
                        tv.setText(response.body().getMsg());
                    }

                    @Override
                    public void onFailure(Call call, Throwable t) {

                    }
                });
                break;
        }
    }
}

 
  

1.基于OKhttp网络请求       遵循RESTful API设计风格

2.通过注解的方式配置网络请求参数    ----简单明了,简洁易懂

3.支持多种数据解析&序列化格式  (如:gson json xml)

4.支持同步 异步请求

5.提供对rxjava的支持   --- 拓展性好

  解耦彻底.封装好



你可能感兴趣的:(java)