REST = RESTful = Representational State Transfer。是在因特网上提供计算机系统之间的互操作性的一种方式。基于Http协议的资源传递,包括JSON、XML和文本等。
统一接口
-
资源识别(Identification of resources)
- URI(Uniform Resource Identifier )
-
资源操作(Manipulation of resources through representations)
- HTTP verbs:GET、PUT、POST、DELETE
-
自描述消息(Self-descriptive messages)
- Content-Type
- MIME-Type
- Media Type: application/javascript、 text/html
-
超媒体(HATEOAS)
- Hypermedia As The Engine Of Application State
REST 服务端实践
1、Spring Boot REST:
-
定义相关
- @Controller
- @RestController
-
映射相关
- @RequestMapping
- @PathVariable:获取路径参数
-
请求相关
- @RequestParam
- @RequestHeader
- @CookieValue
- RequestEntity:包括请求头和请求体等信息配置
-
响应相关
- @ResponseBody
- ResponseEntity:包括返回头和返回体等信息配置
以 @RequestMapping
为例讲解,源码如下,其他的源码亦可如此分析:
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.METHOD, ElementType.TYPE}) //注解作用范围 类或方法
@Retention(RetentionPolicy.RUNTIME) //作用范围,一般自定义注解使用 RetentionPolicy.RUNTIME
@Documented //生成文档
@Mapping //继承@Mapping注解
public @interface RequestMapping {
String name() default "";
@AliasFor("path") //和path等效
String[] value() default {};
@AliasFor("value") //和value等效
String[] path() default {};
RequestMethod[] method() default {}; //可取值 RequestMethod.GET等
String[] params() default {}; //参数名称
String[] headers() default {}; //头信息
String[] consumes() default {}; //客户端请求的数据要求,一般使用MediaType.APPLICATION_JSON_VALUE等
String[] produces() default {}; //服务器返回的数据规定,一般使用MediaType.APPLICATION_JSON_VALUE等
}
举例:
导入依赖:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
返回 XML
格式的数据:
@RestController
public class RestTestController {
@RequestMapping(method = RequestMethod.GET,value = "/test",produces = MediaType.APPLICATION_XML_VALUE)
public User getUserData() {
User user = new User();
user.setName("zhangsan");
user.setAge(18);
return user;
}
}
返回 json
格式的数据:
@RestController
public class RestTestController {
@RequestMapping(method = RequestMethod.GET,value = "/test",produces = MediaType.APPLICATION_JSON_VALUE)
public User getUserData() {
User user = new User();
user.setName("zhangsan");
user.setAge(18);
return user;
}
}
2、Swagger、Spring RestDocs等,这里就不拓展了。
REST 客户端实践
1、Apache HttpClient
导入依赖:
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
HttpClient工具类代码:
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
*@描述: http工具
*/
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
}
2、Spring RestTemplate
,这里就不扩展来了,感兴趣的可以自己去了解下,再微服务当中也常用的技术。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/16057.html