Retrofit 2.0 基本使用

这篇博客介绍了如何在Android项目中使用Retrofit 2.0进行网络请求。首先,引入必要的依赖库,包括Retrofit、Gson、RxJava和OkHttp。接着,创建网络请求的基础配置,如公共请求头和接口定义。然后,构建服务接口,定义GET和POST请求。最后,执行请求并处理返回的ResponseBody,将其转换为指定的对象。

1.引入对应架包

compile 'com.squareup.retrofit2:retrofit:2.1.0' compile

'com.squareup.retrofit2:converter-gson:2.1.0'

//适配器

 compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

//RxJava

compile 'io.reactivex:rxjava:1.1.6'

//RxAndroid compile 'io.reactivex:rxandroid:1.2.1'

compile 'com.squareup.okhttp3:okhttp:3.6.0'

compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'

 

使用:

1. 创建类似请求头的东西,可以公用

String baseUrl = "http://192.168.1.8:8080/RetrofitService/";
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .build();

2. 创建请求体, NewsServlet 与baseUrl 拼接 ,get 方法的  传参 Query  ,post

public interface NewsService {
    //普通call方式
    @GET("NewsServlet")
    Call<ResponseBody> getNews(@Query("id") int id);
}

 

3. 创建 请求

NewsService newsService = createRetrofit().create(NewsService.class);

4. 执行请求,

Call<ResponseBody> answers = newsService.getNews(1);
        answers.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Log(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });

 

5.如果返回结果 为对应的 bean,那么步骤为:

1.

mRetrofit= new Retrofit.Builder()
        .baseUrl(baseurl)
        .addConverterFactory(GsonConverterFactory.create()) //添加这个
        .build();

2.

在上述ResponseBody 替换为 对应的 Object

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值