什么是REST?
REST (REpresentation State Transfer) 描述了一个架构样式的网络系统,比如 web 应用程序。它首次出现在 2000 年 Roy Fielding 的博士论文中,他是 HTTP 规范的主要编写者之一。REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是 RESTful。
Web 应用程序最重要的 REST 原则是,客户端和服务器之间的交互在请求之间是无状态的。从客户端到服务器的每个请求都必须包含理解请求所必需的信息。如果服务器在请求之间的任何时间点重启,客户端不会得到通知。此外,无状态请求可以由任何可用服务器回答,这十分适合云计算之类的环境。客户端可以缓存数据以改进性能。
在服务器端,应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体,它向客户端公开。资源的例子有:应用程序对象、数据库记录、算法等等。每个资源都使用 URI (Universal Resource Identifier) 得到一个惟一的地址。所有资源都共享统一的界面,以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、PUT、POST 和 DELETE。Hypermedia 是应用程序状态的引擎,资源表示通过超链接互联。
传统的Rest封装
传统的Rest封装是通过Httpclient实现Rest封装。通过HttpClient的API实现Rest的 GET、PUT、POST 和 DELETE操作。传统的HttpClient操作Rest的例子如下(Activiti Rest代码):
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient; public class TestLogin { public static void main(String[] args) throws Exception, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://localhost:8080/activiti-rest/service/login"); StringEntity input = new StringEntity("{\"userId\":\"kermit\",\"password\":\"kermit\"}"); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); }}
传统的Rest封装是通过存在一下一些缺点:
1)需要对输入输出参数进行组装,会存在大量的对象转换的代码;
2)需要处理一些连接性的源代码,对http connect进行close;
3)提高代码复杂度
Retrofit封装(http://square.github.io/retrofit/)
retrofit是对Restful的简洁封装,可以提高Restful的使用效率。提现模式为:
public interface GitHubService { @GET("/users/{user}/repos") List<Repo> listRepos(@Path("user") String user); }
生成源代码
RestAdapter restAdapter = new RestAdapter.Builder() .setServer("https://api.github.com") .build(); GitHubService service = restAdapter.create(GitHubService.class);
Retrofit完整例子 http://blog.youkuaiyun.com/arjick/article/details/18263201