Retrofit用法详解之一(无参数get请求)

Retrofit是Square公司开发的一款针对Android网络请求的框架,Retrofit2底层基于OkHttp实现的.

一、如何使用

    1.配置网络访问权限

    <uses-permission android:name="android.permission.INTERNET"/>

    2.使用Retrofit之前需要先在build gridle中引入三个包,配置如下:

    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
      compile 'com.squareup.okhttp:okhttp:2.5.0'
      compile 'com.squareup.okio:okio:1.6.0'
 引入完这三个包就可以使用Retrofit来访问网络了
3.get请求
   (1)Application中添加一个访问网络的静态变量(千万不要网络配置application)  
      public static final String BASE_URL = "http://service.meiyinkeqiu.com/service/";
  (2)使用之前需要先创建一个业务访问接口如:	
      public interface BlueService {
          @GET("ads/cptj")                
           Call getSearchBooks();
        }
   (3)然后创建一个bean,代码如下:

public class GuangGaoBean {

    private List ads;

    private List> dropdown;

    public List getAds() {

        return ads;

    }

    public void setAds(List ads) {

        this.ads = ads;

    }

    public List> getDropdown() {

        return dropdown;

    }

    public void setDropdown(List> dropdown) {

        this.dropdown = dropdown;

    }

    public static class AdsBean {

        private int id;

        private String imgsrc;

        private String url;

        private String type;

        private int adsorder;

        public int getId() {

            return id;

        }

        public void setId(int id) {

            this.id = id;

        }

        public String getImgsrc() {

            return imgsrc;

        }

        public void setImgsrc(String imgsrc) {

            this.imgsrc = imgsrc;

        }

        public String getUrl() {

            return url;

        }

        public void setUrl(String url) {

            this.url = url;

        }

        public String getType() {

            return type;

        }

        public void setType(String type) {

            this.type = type;

        }

        public int getAdsorder() {

            return adsorder;

        }

        public void setAdsorder(int adsorder) {

            this.adsorder = adsorder;

        }

    }

}

(4)然后就可以访问网络了

new Thread(){

    @Override

    public void run() {

        Retrofit retrofit = new Retrofit.Builder()

                .baseUrl(App.BASE_URL)

                .addConverterFactory(GsonConverterFactory.create())

                .build();

        BlueService service = retrofit.create(BlueService.class);

        service.getSearchBooks().enqueue(new Callback() {

            @Override

            public void onResponse(Response response, Retrofit retrofit) {

                Log.e("访问网络",response.body().getAds().size()+"");

            }

            @Override

            public void onFailure(Throwable t) {

            }

        });

    }

}.start();

 

你可能感兴趣的:(Retrofit用法详解之一(无参数get请求))