Retrofit的使用

2022-04-04  本文已影响0人  BillyJean

Retrofit相关依赖

  implementation'com.squareup.retrofit2:retrofit:2.9.0'
  implementation'com.squareup.retrofit2:converter-gson:2.9.0'

基本使用步骤:

在进行请求之前,要先创建一个接口:

public interface HttpBinService {
    //所有的请求都要以注解的方式进行声明

    //有两种提方式:FormUrlEncoded(对应key-value形式)或者MulityPart(文件形式)
    //@Field("xxx")这里面是传的参数的名字
    //https:www.httpbin.org/post xxx=value
    //括号后面是拼接在请求BaseUrl后面的,"https://www.httpbin.org/get?username=张三&pwd=456"
   //这里是以表单的形式提交的
    @POST("post")
    @FormUrlEncoded
    Call<ResponseBody> post(@Field("username") String name, @Field("pwd") String password);

    //get请求要传参数,使用的就是Query;post请求要传参数,使用的就是Field
    @GET("get")
    Call<ResponseBody> get(@Query("username") String username, @Query("pwd") String password);

}

接口创建好之后在对应位置声明成员变量和初始化retrofit和接口实例化对象

  private Retrofit retrofit;
  private HttpBinService binService;

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

        retrofit = new Retrofit.Builder().baseUrl("https:www.httpbin.org").build();
        binService = retrofit.create(HttpBinService.class);
    }

1.POST请求
 //retrofit中的post请求,基础使用
    public void post(View view) {
        Call<ResponseBody> call = binService.post("xxx", "123");
        call.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) {
            }
        });
    }
public interface HttpBinService {
  //此处没有@FormUrlEncoded注解
  @POST("post")
    Call<ResponseBody> postBody(@Body RequestBody body);
}

所以在代码请求时候需要自己来封装

  public void postBody(View view) {
        //手动封装key-value,请求结果与添加了@FormUrlEncoded注解的形式相同
       //相对于添加@FormUrlEncoded来说更加灵活
        FormBody formBody = new FormBody.Builder()
                .add("a","1").add("b","2").build();
        Call<ResponseBody> bodyCall = binService.postBody(formBody);
        bodyCall.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) {
            }
        });
    }
public interface HttpBinService {
//此时拼接出来的地址形式为: "https://www.httpbin.org/path",
//添加了头部(用于区分android和ios),同时以表单形式提交了用户名和密码
 @POST("{id}")
    @FormUrlEncoded
    Call<ResponseBody> postInPath(@Path("id") String path
                                  , @Header("os") String os
                                  , @Field("username") String name
                                  , @Field("pwd") String pwd);
}

实际请求如下:

  public void usePath(View view) {
        Call<ResponseBody> call = binService.postInPath("post","android","xxxxx","123456");
        call.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) {

            }
        });
    }
public interface HttpBinService {
  //多个头
    @Headers({"os:android", "version:1.0.0"})
    @POST("post")
    Call<ResponseBody> postWithHeaders();
}

方法调用

 public void usePostHeaders(View view) {
        Call<ResponseBody> call = binService.postWithHeaders();
        call.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) {

            }
        });
    }
public interface HttpBinService {
  //url注解,也要加上相关注解POST或者GET,指定的是一个完整的地址,不看BaseUrl,只看传递进来的地址
    @POST
    Call<ResponseBody> postInUrl(@Url String url);
}

请求地址要自己指定

    public void usePostInUrl(View view) {
       // 自己指定请求地址
        Call<ResponseBody> call = binService.postInUrl("https://www.httpbin.org/post");
        call.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) {

            }
        });
    }
2.GET请求
 //retrofit中的get请求,基础使用
    public void get(View view) {
        Call<ResponseBody> call = binService.get("bigzing", "456");
        call.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) {
            }
        });
    }
上一篇 下一篇

猜你喜欢

热点阅读