Retrofit用法

参考文章:https://www.jianshu.com/p/7efdc3477269

第一步:集成

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

   添加网络权限:

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

第二步:创建Retrofit对象

Retrofit retrofit = new Retrofit.Builder() 
                                .addConverterFactory(GsonConverterFactory.create())//解析方法                                 
                                //这里建议:- Base URL: 总是以/结尾;- @Url: 不要以/开头
                                .baseUrl("http://www.wangyinews.com.cn/")                                 
                                .build();

第三步:申明接口

public interface NewsService { 
    @GET("News/{newsId}") 
    Call<News> getNews(@Path("newsId") String newsId); 
}

若需要重新定义接口地址可以使用@Url,例:

@GET
    Call<List<CaigenActivitySubjectsBean>> getActivitySubjectsList(@Url String url,
            @QueryMap Map<String, String> map);

相关参数注解:

@Path : URL中带有参数,用于补全地址,例如:

http://102.10.10.132/api/News/1
@GET("News/{newsId}")
    Call<NewsBean> getItem(@Path("newsId") String newsId);

@Query : 参数在URL的问号之后,例如:

http://102.10.10.132/api/News?newsId=1
@GET("News")
    Call<NewsBean> getItem(@Query("newsId") String newsId);

@QueryMap : 多个参数在URL问号之后,且个数不确定,例如:

http://102.10.10.132/api/News?newsId=1&type=类型1...
@GET("News")
    Call<NewsBean> getItem(@QueryMap Map<String, String> map);

@Field : 用于Post请求,提交单个数据,例如:

    http://102.10.10.132/api/Comments/1    需要补全URL,且post提交的body参数只有一条

@FormUrlEncoded
@POST("Comments/{newsId}") 
  Call<Comment> reportComment( @Path("newsId") String commentId, @Field("reason") String reason);

注意:用到@Field时必须加@FormUrlEncoded

@Body : 相当于多个@Field,以对象的形式提交,例如:

@POST("Comments/{newsId}") 
 Call<Comment> reportComment( @Path("newsId") String commentId, @Body CommentBean bean);

第四步:创建访问API的请求

NewsService api = retrofit.create(NewsService .class);
Call<News> call = api.getNews("1");

第五步:调用

    同步调用:

News news = call.execute();

    异步调用:

call.enqueue(new Callback<News>(){ 
    @Override 
    public void onResponse(Response<News> response) { 
        //成功返回数据后在这里处理,使用response.body();获取得到的结果 
        News news = response.body(); 
    } 
    @Override 
    public voidonFailure(Throwable t) { 
        //请求失败在这里处理 
    } 
});

第六步:Retrofit允许取消请求

call.cancel(); 
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值