Retrofit简单使用(Kotlin)

本文介绍了在Kotlin中如何配置并使用Retrofit进行网络访问,包括基本的接口定义和调用方法。
Retrofit是Square公司开源的一个基于OkHttp实现的Android网络请求框架,它将我们自己开发的底层的代码和细节都封装了起来。 
https://github.com/square/retrofit 
http://square.github.io/retrofit/

首先要进行配置

在/app/build.gradle配置中加入

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

接下来就是网络访问接口

public interface ApiService {

    //注解后面是路径,,,但是这个路径比较特殊
    //https://www.zhaoapi.cn/----baseUrl ----http://163.16.11.22:8080/
    // product/getProductCatagory----相对路径----linzhiling/lingzhiling.jpg

    @GET("product/getProductCatagory")
    Call<CategaryBean> getCategary();

    //https://www.zhaoapi.cn/product/searchProducts?keywords=笔记本&page=1&source=android

    @GET("product/searchProducts")
    Call<SearchBean> getSearch(@QueryMap Map<String,String> map);

    //post传递的是表单数据
    @FormUrlEncoded
    @POST("product/searchProducts")
    Call<SearchBean> postSearch(@FieldMap Map<String,String> map);

    @FormUrlEncoded
    @POST("product/searchProducts")
    Call<SearchBean> postSearch_02(@Field("keywords") String keywords,@Field("page") String page,@Field("source") String source);

    @GET("users/{user}/repos") //{user}请求路径上的占位符
    Call<ResponseBody>  getBlog(@Path("user") String user);
    // 访问的API是:https://api.github.com/users/{user}/repos
    // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用)

}
public class MainActivity extends AppCompatActivity {

    private TextView text_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text_view = findViewById(R.id.text_view);

    }


    // Unable to create converter转换器 for class com.dash.a05_retrofit.CategaryBean
    //不能够为CategaryBean创建一个转换器---response.body().string()---json字符串--Gson->CategaryBean
    //json xml jackSon --->对应着不同的转换器
    public void getCategory(View view) {

        Retrofit retrofit = new Retrofit.Builder()//构建者模式
                .baseUrl(Constant.BASE_URL)//设置baseUrl
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .build();

        //需要使用retrofit创建一个网络请求的接口
        ApiService apiService = retrofit.create(ApiService.class);

        Call<CategaryBean> call = apiService.getCategary();

        call.enqueue(new Callback<CategaryBean>() {
            @Override
            public void onResponse(Call<CategaryBean> call, Response<CategaryBean> response) {
                if (response.isSuccessful()) {
                    CategaryBean categaryBean = response.body();

                    //主线程还是子线程????---主线程,,retrofit自动完成了线程的切换
                    text_view.setText(categaryBean.getMsg());
                }
            }

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

            }
        });

    }

    public void getCategory_02(View view) {

        //这部分代码其实是写在model里面的

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService apiService = retrofit.create(ApiService.class);

        Map<String, String> params = new HashMap<>();
        params.put("keywords","笔记本");
        params.put("page","1");
        params.put("source","android");

        //Call<SearchBean> call = apiService.getSearch(params);

        //Call<SearchBean> call = apiService.postSearch(params);

        Call<SearchBean> call = apiService.postSearch_02("笔记本", "1", "android");

        call.enqueue(new Callback<SearchBean>() {
            @Override
            public void onResponse(Call<SearchBean> call, Response<SearchBean> response) {
                text_view.setText(response.body().getData().get(0).getTitle());
            }

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

            }
        });

    }
}

还有不懂的话可以去看一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值