rest api

[size=large] 要弄清楚什么是RESTful API,首先要弄清楚什么是REST。REST -- REpresentational State Transfer,英语的直译就是“表现层状态转移”。如果看这个概念,估计没几个人能明白是什么意思。那下面就让我来用一句人话解释一下什么是RESTful:URL定位资源,用HTTP动词(GET,POST,PUT,DELETE)描述操作

Resource:资源,即数据。
Representational:某种表现形式,比如用JSON,XML,JPEG等;
State Transfer:状态变化。通过HTTP动词实现。

所以RESTful API就是REST风格的API。 那么在什么场景下使用RESTful API呢?在当今的互联网应用的前端展示媒介很丰富。有手机、有平板电脑还有PC以及其他的展示媒介。那么这些前端接收到的用户请求统一由一个后台来处理并返回给不同的前端肯定是最科学和最经济的方式,RESTful API就是一套协议来规范多种形式的前端和同一个后台的交互方式。

RESTful API由后台也就是SERVER来提供前端来调用。前端调用API向后台发起HTTP请求,后台响应请求将处理结果反馈给前端。也就是说RESTful 是典型的基于HTTP的协议。那么RESTful API有哪些设计原则和规范呢?

1,资源。首先是弄清楚资源的概念。资源就是网络上的一个实体,一段文本,一张图片或者一首歌曲。资源总是要通过一种载体来反应它的内容。文本可以用TXT,也可以用HTML或者XML、图片可以用JPG格式或者PNG格式,JSON是现在最常用的资源表现形式。


2,统一接口。RESTful风格的数据元操CRUD(create,read,update,delete)分别对应HTTP方法:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源,这样就统一了数据操作的接口。


3,URI。可以用一个URI(统一资源定位符)指向资源,即每个URI都对应一个特定的资源。要获取这个资源访问它的URI就可以,因此URI就成了每一个资源的地址或识别符。一般的,每个资源至少有一个URI与之对应,最典型的URI就是URL。


4,无状态。所谓无状态即所有的资源都可以URI定位,而且这个定位与其他资源无关,也不会因为其他资源的变化而变化。有状态和无状态的区别,举个例子说明一下,例如要查询员工工资的步骤为第一步:登录系统。第二步:进入查询工资的页面。第三步:搜索该员工。第四步:点击姓名查看工资。这样的操作流程就是有状态的,查询工资的每一个步骤都依赖于前一个步骤,只要前置操作不成功,后续操作就无法执行。如果输入一个URL就可以得到指定员工的工资,则这种情况就是无状态的,因为获取工资不依赖于其他资源或状态,且这种情况下,员工工资是一个资源,由一个URL与之对应可以通过HTTP中的GET方法得到资源,这就是典型的RESTful风格。

来一段java的rest api 实例

[b]httpPost:[/b]

public static JSONObject httpPost(String url, String strParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(1000000).setConnectTimeout(1000000).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36");
try {
if (null != strParam) {
StringEntity stringEntity = new StringEntity(strParam,"UTF-8");
// stringEntity.setContentEncoding("UTF-8");
httpPost.setEntity(stringEntity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
String str = EntityUtils.toString(result.getEntity(), "utf-8");
//把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
if (result.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.error("delete请求提交失败:" + url);
}
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}finally {
httpPost.releaseConnection();
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonResult;
}

[b]httpGet:[/b]
public static JSONObject httpGet(String url) {
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
System.out.println("HTTPGET:"+url);
HttpGet request = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(1000000).setConnectTimeout(1000000).build();
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
jsonResult = JSONObject.parseObject(strResult);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.error("get请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
} finally {
request.releaseConnection();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonResult;
}
[b]httpDelete[/b]
public static JSONObject httpDelete(String url) {
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
System.out.println("HTTPDelete:"+url);
HttpDelete request = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000000).setConnectTimeout(10000000).build();
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
jsonResult = JSONObject.parseObject(strResult);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.error("delete请求提交失败:" + url);
}
} catch (IOException e) {
logger.info(e.getMessage(),e);
logger.error("delete请求提交失败:" + url, e);
} finally {
request.releaseConnection();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonResult;
}

[b]httpPut:[/b]
public static JSONObject httpPut(String url,String strParam) {
JSONObject jsonResult = null;
String responseContent = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(100000).setConnectTimeout(100000).build();
httpPut.setConfig(requestConfig);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","*/*");
try {
if (null != strParam) {
StringEntity stringEntity = new StringEntity(strParam,"utf-8");
stringEntity.setContentEncoding("UTF-8");
httpPut.setEntity(stringEntity);
}
CloseableHttpResponse response = client.execute(httpPut);
responseContent = EntityUtils.toString(response.getEntity(),"utf-8");
jsonResult = JSONObject.parseObject(responseContent);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.error("put请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("put请求提交失败:" + url, e);
} finally {
httpPut.releaseConnection();
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonResult;
}[/size]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值