简单Retrofit2.0实现请求网络

一.添加依赖

compile 'com.squareup.retrofit2:retrofit:2.0.0'  
compile 'com.squareup.retrofit2:converter-gson:2.0.2' 

.编写工具类

package com.bwie.skn.simulationoneweek.utils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * author:Created by Conan on 2017/12/30.
 */

public class RetrofitUtils {
    public static final String BASE_URL = "http://result.eolinker.com/";//请求头
    private final Retrofit mRetrofit;

    public static class SINGLE_HOLDER{
        public static final RetrofitUtils INSTANCE = new RetrofitUtils(BASE_URL);
    }

    public static RetrofitUtils getInstance(){
        return SINGLE_HOLDER.INSTANCE;
    }

    private RetrofitUtils(String baseUrl){
        mRetrofit = buildRetrofit();

    }
    //自定义OkHttpClient(可以不写)
    private OkHttpClient buildOkHttpClient(){
        return new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
    }
    //Retrofit的设置
    private Retrofit buildRetrofit(){
        return new Retrofit.Builder()
                .client(buildOkHttpClient())
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    //返回的数据
    public  T create(Class clazz){
        return mRetrofit.create(clazz);
    }
}

三.编写工具类接口


package com.bwie.skn.simulationoneweek.interfaces;


import com.bwie.skn.simulationoneweek.bean.WeekBean;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * author:Created by Conan on 2017/12/30.
 */

public interface RetrofitApi {
    @GET("umIPmfS6c83237d9c70c7c9510c9b0f97171a308d13b611")//请求体
    Call getBean (@Query("uri") String uri);
}


四.工具类的使用


RetrofitApi retrofitApi = RetrofitUtils.getInstance().create(RetrofitApi.class);//连接接口
        Call weekCall = retrofitApi.getBean("homepage");//传请求参数
        weekCall.enqueue(new Callback() {
            //请求成功
            @Override
            public void onResponse(Call call, Response response) {
                WeekBean body = response.body();
                WeekBean.DataBean data = body.getData();
                iweekPresenter.onSuccess(data);
            }
            //请求失败
            @Override
            public void onFailure(Call call, Throwable throwable) {
                iweekPresenter.onFailed(throwable.getMessage());
            }
        });



你可能感兴趣的:(android)