Retrofit初体验

来源:互联网 发布:nothing软件怎么样 编辑:程序博客网 时间:2024/06/05 09:25


刚刚接触Retrofit,网上资料大多直入主题,刚开始看还真的看不太懂。现在自己记录一下学习中遇到的问题;

 

1、Rerofit  如何获取Json数据?ResponseBody

2、Post 方法 报错:@FormUrlEncoded

3、Url问题:baseURL只能识别api之前(.com)

可变URL/会被解析为%2F

 

4Gson 自动解析.addConverterFactory(GsonConverterFactory.create())

 

 

 

编写 Retrofit

1、编写API服务代码

API 服务 指 请求网络的接口

1. public interface ApiService {  

2.     @GET("service/getIpInfo.php")  

3.     Call<GetIpInfoResponse> getIpInfo(@Query("ip") String ip);  

4. }  

请求方式

(1)GET @GET("service/getIpInfo.php")  

 可变参数:@Query(sort) Sring sort

可变多个参数 @QueryMap Map<String,String> map

可变URL@Path(id) int id

@GET("service/{id}/getIpInfo.php")     自动替换

(2)POST:

@POST("users/new")

Call<User> createUser(@Body User user);

表单形式上传参数:

@FormUrlEncoded

@POST("user/edit")

Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

复杂参数Multipart  

@Multipart

@PUT("user/photo")

Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);

(3)Head

@Headers("Cache-Control: max-age=640000")

@GET("widget/list")

Call<List<Widget>> widgetList();

 

 

@Headers({

    "Accept: application/vnd.github.v3.full+json",

    "User-Agent: Retrofit-Sample-App"

})

@GET("users/{username}")

Call<User> getUser(@Path("username") String username);

@GET("user")

Call<User> getUser(@Header("Authorization") String authorization)

 

 

注意 Tips:

(1)GetIpInfoResponse:自己编写的Bean

2)如果想获取Json字符串:Call<ResponseBody> getIpInfo(@Query("ip") String ip);

3post表单 @FormUrlEncoded

 

2、网络请求代码

Retrofit retrofit = new Retrofit.Builder()

    .baseUrl("https://api.github.com/")

    .build();

GitHubService service = retrofit.create(GitHubService.class);

 

 

 

 

 

 

 

 

 

 

 

 

0 0