android 介绍Retrofit的简单使用

1.导包:


compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依赖包


2.Retrofit需要定义一个接口,用来返回我们的Call对象:


public interface GetRequest_Interface {

    @GET("toutiao/index?type=top&key=dbedecbcd1899c9785b95cc2d17131c5 ")
    Call<Bean>  getCall();

    @FormUrlEncoded
    @POST("toutiao/index")
    Call<Bean>  postCall(@Field("key") String key, @Field("type") String type);

    @GET("toutiao/index?type=top&key=dbedecbcd1899c9785b95cc2d17131c5 ")
    Call<String>  getStringCall();
}
3. Retrofit对象来进行请求:

 //get请求
/* Retrofit retrofit = new Retrofit.Builder()
         .baseUrl("http://v.juhe.cn/") //设置网络请求的Url地址
         .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
         .build();
 GetRequest_Interface getRequest_interface = retrofit.create(GetRequest_Interface.class);
 Call<Bean> call = getRequest_interface.getCall();
 call.enqueue(new Callback<Bean>() {
     @Override
     public void onResponse(Call<Bean> call, Response<Bean> response) {
         Bean body = response.body();
     }

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

     }
 });*/
//post请求
 /*Retrofit retrofit = new Retrofit.Builder()
         .baseUrl("http://v.juhe.cn/")
         .addConverterFactory(GsonConverterFactory.create())
         .build();
 GetRequest_Interface getRequest_interface = retrofit.create(GetRequest_Interface.class);
 Call<Bean> beanCall = getRequest_interface.postCall("dbedecbcd1899c9785b95cc2d17131c5", "top");
 beanCall.enqueue(new Callback<Bean>() {
     @Override
     public void onResponse(Call<Bean> call, Response<Bean> response) {
         Bean body = response.body();
         System.out.println(body.toString());
     }

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

     }
 });*/
 //String类型请求
 Retrofit retrofit = new Retrofit.Builder()
         .baseUrl("http://v.juhe.cn/")
         .addConverterFactory(ScalarsConverterFactory.create())//设置数据解析器
         .build();
 GetRequest_Interface getRequest_interface = retrofit.create(GetRequest_Interface.class);
 Call<String> stringCall = getRequest_interface.getStringCall();
 stringCall.enqueue(new Callback<String>() {
     @Override
     public void onResponse(Call<String> call, Response<String> response) {
         System.out.println(response.body());
     }
     @Override
     public void onFailure(Call<String> call, Throwable t) {

     }
 });


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值