Android——Retrofit

2022/2/14 6:12:13

本文主要是介绍Android——Retrofit,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Retrofit

简介:对OkHttp的封装

    根据请求接口,获取响应

 

注解

  方法注解

    @GET:声明为GET请求方式

    @POST:声明为POST请求方式

    @HTTP:声明为自定义请求方式

 

  标记注解

    @FormUrlEncoding:对post请求,声明请求体为表单

    @Multipart:对post请求,声明请求体为多类型

    @Streaming:对post请求,声明请求体为流

 

  参数注解

    @Query:对get请求:设置接受的参数名

    @Field:对post请求:设置接受的参数名

    @QueryMap:对get请求:设置接受参数为Map<String,String>集合

    @FieldMap:对post请求:设置接受参数为Map<String,String>集合

    

  其他注解

    @Path

    @Header

    @Headers

    @Url

 

方法

   (Retrofit)

   Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();

    返回值类型:Retrofit

    返回值作用:生成Retrofit对象

    作用:根据基本url,生成Retrofit对象

 

   Retrofit retrofit.create(HttpbinService.class);

    参数:

      HttpbinService.class 是请求接口对象

    返回值:HttpbinService 接口对象

    返回值意义:获取请求接口对象

    作用:获取请求接口对象,调用请求接口定义的方法

  

  

使用步骤

  1. 生成请求接口 service:定义请求方式,请求体类型,接受参数名

  2. 生成Retrofit对象,将请求接口传入

  3. 调用生成接口对象中的方法,传参数值,enquqe获取响应值

 

使用

// 1. 生成请求接口定义,方式,请求体,参数名
public interface HttpbinService3 {
    // 设置请求方式,请求体类型,表单
    @POST("post")
    @FormUrlEncoded
    Call<ResponseBody> post(@Field("userName")String userName,@Field("password")String password);
}


// 2. 生成retrofit对象,传入接口,调用接口对象定义方法
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
        HttpbinService3 httpbinService3 = retrofit.create(HttpbinService3.class);
        httpbinService3.post("lance","123").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Log.i(TAG, "onResponse: "+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

            }
        });

 



这篇关于Android——Retrofit的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程