Retrofit基本使用

1.注解:

1.1 编码方式注解:

表单数据提交

    @FormUrlEncoded 	//使用application/x-www-form-urlencoded的编码方式提交表单,默认的方式
    @Multipart			//使用multipart/form-data的编码方式提交带文件的表单
    @Streaming			//表示数据以流的形式返回,比如获取图片或视频流

这类注解直接作用于方法,例如:

	@POST("/login")
    @FormUrlEncoded
    Call<Response> login(@Field("username") String name, @Field("password") String password);
1.2 设置网络请求方法:

这些方法也直接作用于方法,标识请求使用使用的方法,常用的有:@GET @POST @PUT @DELETE @HTTP

其中HTTP用来代替GET或POST等方法,注解提供了更多自定义的属性,例如:

	@HTTP(method = "POST", path = "login", hasBody = true)
	@FormUrlEncoded
	Call<Response> login(@Field("username") String name, @Field("password") String password);
1.3 其他参数注解:
Type1:对URL处理加工:

BaseUrl在RetrofitBuilder中设置:

	Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.bilibili.com/manage/") 					//这里的baseUrl记得以/结尾
        .build();

1)如果Path使用相对路径(即路径开头不带/号):

	// http://www.bilibili.com/manage/userdata?username=xiaoming&id=123456
    @GET("userdata?username=xiaoming&id=123456")
    Call<Response> getUser();

2)如果Path使用绝对路径(即路径开头有/号):

	// http://www.bilibili.com/userdata?username=xiaoming&id=123456
    @GET("/userdata?username=xiaoming&id=123456")
    Call<Response> getUser();

3)如果Url是动态的,即Url的一部分需要由参数来决定,就需要使用@Path拼接Url:

	// http://www.bilibili.com/userdata/xxx/repos
	@GET("/userdata/{user}/repos")
	Call<Response> getUser(@Path("user") String user);

4) 用@Url优先使用参数中的Url

	@GET
	Call<ResponseBody> getData(@Url String url);
Type2: 为GET请求添加参数:

上面的例子中,请求的参数被写死在Path中,非常不灵活,所以GET方法提供了动态配置GET参数的方法:

	//http://www.xxx.com/userdata?name=xxx&id=xxx
	@GET("userdata")    
    Call<String> getUser(@Query("name") String username,@Query("id") String userId);

	@GET("userdata")    
    Call<String> getUser(@QueryMap Map<String, Object> map);
Type3: 用POST提交表单数据:

1)@Field 和 @FieldMap
配合@FormUrlEncoded注解使用,以application/x-www-form-urlencoded的方式提交表单数据

	@POST("/login")
    @FormUrlEncoded
    Call<ResponseBody> login(@Field("username") String name, @Field("password") String password);

	@POST("/login")
    @FormUrlEncoded
    Call<ResponseBody> loginGroup(@FieldMap Map<String, Object> map);

2)@Part 和 @PartMap
配合@Multipart注解使用,以multipart/form-data的方式提交带文件的表单数据

	@POST("/login")
    @Multipart
    Call<ResponseBody> login(@Part("username") String name, @Part("passfile") MultipartBody.Part file);

	@POST("/login")
    @Multipart
    Call<ResponseBody> loginGroup(@PartMap Map<String, RequestBody> map);

3)@Body
把自定义的数据类型传给服务器

	@POST("/login")
	Call<ResponseBody> login(@Body Request request);
Type4:HEAD设置请求头:
	//@Headers作用于方法,用于添加固定的请求头,
	@Headers("Authorization: authorization")
	@GET("data")
	Call<User> getData()
	
	//@Header作用于参数,用于添加不固定的请求头
	@GET("data")
	Call<User> getData(@Header("Authorization") String authorization)

2.使用:

1.基本使用:

依赖:

	implementation'com.squareup.retrofit2:retrofit:2.5.0'
	implementation'com.squareup.okhttp3:okhttp:3.12.2'

添加网络权限

	 <uses-permission android:name="android.permission.INTERNET" />

创建Api接口

	public interface Api {
  		  @GET("users")
  		  Call<ResponseBody> getUser(@Query("id") String userId);
	}
	new Retrofit.Builder().baseUrl(url).build();
	
	Api api = new Retrofit.Builder().baseUrl(url).build().create(Api.class);
	Call<ResponseBody> call = api.getUser("123456");
	//同步
	new Thread(()->{
           try {
                Response<ResponseBody> response = call.execute();
           } catch (Exception e) {
                e.printStackTrace();
           }
    });
    
    //异步
	call.enqueue(new Callback<ResponseBody>() {
     	@Override
     	public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
      	}

     	@Override
     	public void onFailure(Call<ResponseBody> call, Throwable t) {
      	}
	});
2.用Gson自动解析结果:

添加Gson依赖:

    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

根据返回的Json结构创建POJO类

	public class User {
		private String username;
		private int age;
		...
	}

修改接口

	public interface Api {
  		  @GET("users")
  		  Call<User> getUser(@Query("id") String userId);
	}

添加Gson转换器:

	new Retrofit.Builder()
          .baseUrl(url)
          .addConverterFactory(GsonConverterFactory.create(gson))		
          .build();
	Api api = retrofit.create(Api.class);
	Call<User> call = api.getUser("123456");
	//同步
	Response<User> response = call.execute();		
	//异步
	call.enqueue(new Callback<User>() {
          @Override
          public void onResponse(Call<User> call, Response<User> response) { 
          }

          @Override
          public void onFailure(Call<User> call, Throwable t) {
          }
    });
3.Rxjava适配器:

依赖:

    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
    implementation'io.reactivex.rxjava2:rxjava:2.2.7'

修改接口:

	public interface Api {
  		  @GET("users")
  		  Observable<User> getUser(@Query("id") String userId);
	}

添加Rxjava适配器:

	new Retrofit.Builder()
          .baseUrl(url)
          .addConverterFactory(GsonConverterFactory.create(gson))	
          .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
          .build();
	Api api = retrofit.create(Api.class);
	Observable<User> call = api.getUser("123456");

其他:Retrofit源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值