Retrofit——A type-safe HTTP client for Android and Java(The first part)
2016-08-21 22:11
706 查看
一,介绍
Retrofit将你的http接口API转换成项目中的一个java的接口。public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }
Retrofit会自动为上面的Service生成一个实现类。
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); GitHubService service = retrofit.create(GitHubService.class);
每次调用的时候,创建的接口的实现类会产生一个异步或者同步的http请求到远程的web服务器上面。
Call<List<Repo>> repos = service.listRepos("octocat");
使用注解的方式来描述http请求: 1,支持url参数和查询参数 2,对象转换成请求体,即对json对象的支持 3,多种请求体,文件等也支持(翻译的好土气呀。。。
)
二,API声明
使用接口上的方法注解和请求参数来说明一个请求时如何被处理的。三,请求方法
每个方法都必须有一个http注解来提供请求请求和相关联的URL。这里有五种支持的注解形式:GET,POST,PUT,DLETE,HEAD。相关的请求URL放在请求注解中。@GET("users/list")
同时,你也可以直接在URL中提供请求参数:
@GET("users/list?sort=desc")
四,URL操作
请求参数能被动态更新---by方法中的占位符。一个请求块是用’{}‘——这个符号包围的。一个对应的参数必须被@Path注解,并且使用相同的参数名字。@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId);
请求参数也能被添加:
@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
例如,下面使用一个map来做栗子:
@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
翻译了一部分,感觉上面的东西好像是外星人写的。。。宝宝会继续更的!希望能忍着翻译完,更希望看过的人不要打我。
相关文章推荐
- Retrofit——A type-safe HTTP client for Android and Java(The first part)
- Retrofit2,A type-safe HTTP client for Android and Java
- Retrofit A type-safe HTTP client for Android and Java
- Retrofit A type-safe HTTP client for Android and Java
- An HTTP & HTTP/2 client for Android and Java applications OkHttp
- Development and remote installation of Java service for the Android Devices
- 解决The method getCookieStore() is undefined for the type HttpClient
- Android:Java:编译/运行:提示:The method X is undefined for the type Y
- What is the difference between HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR
- Java 被访问时报 the method getDispatcherType() is undefined for the type HttpServletRequest
- HTTP Response Caching for Java and Android
- fragment 里需要activity。Android-The method findViewById(int) is undefined for the type first (Fragment)
- Ubuntu 9.10, Java 5 and the Android Open Source Project
- My first blog of learning Java and android
- [Drupal] duplicated entry for meta http-equiv="Content-Type" in the head-area
- (Sharepoint 2010) Change the background and font color of text for a web part header
- How to Change the Icon for a File Type in Windows 7 and Vista(转)
- Website for the introduction to Matlab and Java
- Website for the introduction to Matlab and Java
- 在与sap系统集成时遇到的问题.sap系统发布一webservice,java(xfire)作为客户端调用,调用时抛出如下异常: Wrong Content-Type and empty HTTP-Body received: ("HTTP Code 20