美文网首页
Retrofit 2.0使用

Retrofit 2.0使用

作者: 泡泡之意境 | 来源:发表于2018-06-28 18:03 被阅读47次

    最近自己研究了下Retrofit 2.0的用法,网络上也有各种相关的文章,但是都大同小异,自己还是有些地方不明白,废了半天劲儿,今天主要写一下POST请求方式的用法,也是自己记录一下。

    1、首先,由于我只是用了Retrofit 2.0,配合Gson使用,所以需要导入包:

    compile'com.squareup.retrofit2:retrofit:2.0.2'
    compile'com.squareup.retrofit2:converter-gson:2.0.2' // 用Gson解析json的转换器
    

    2、创建一个接口,定义一个方法,用注解的样式说明不同参数的用途(我是这么理解的)
    当没有参数时写法如下:

    public interface PostRequest_Interface {
        @POST
        Call<Ha> getCall(@Url String url);
    }
    

    当有参数时写法如下:

    public interface PostRequest_Interface {
        @POST
        @FormUrlEncoded
        Call<Ha> getCall(@Url String url,@Field("userId") String userId);
    }
    

    注:当有参数时,@POST和@FormUrlEncoded配合使用,参数@Field是代表单个,也可使用@FieldMap
    3、创建Retrofit对象

     //创建Retrofit对象
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://xxxxxx") // 设置 网络请求 Url
                    .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                    .client(httpClient)
                    .build();
    

    4、创建 网络请求接口 的实例,实现接口方法(对应的是无参数接口的用法)

     // 创建 网络请求接口 的实例
            PostRequest_Interface request = retrofit.create(PostRequest_Interface.class);
    
            //对 发送请求 进行封装
            Call<Ha> call = request.getCall("xxxxx");
    
    

    5、发送网络请求(异步)

    //发送网络请求(异步)
            call.enqueue(new Callback<Ha>() {
    
                //请求成功时回调
                @Override
                public void onResponse(Call<Ha> call, Response<Ha> response) {
                    // 请求处理,输出结果
                    System.out.println("请求成功");
                }
    
                //请求失败时回调
                @Override
                public void onFailure(Call<Ha> call, Throwable throwable) {
                    System.out.println("请求失败");
                }
            });
    

    到这就实现了请求接口,并接收数据了。

    相关文章

      网友评论

          本文标题:Retrofit 2.0使用

          本文链接:https://www.haomeiwen.com/subject/vrrnyftx.html