架构设计之REST

一、REST概念是什么?

表现层状态传递(Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种万维网软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性

二、前后端通信请求方式?

REST要求客户端向服务端发出请求以获得或修改服务器上的数据(即通过HTTP请求操作服务器)。

(1)HTTP动词,它定义了要执行的操作类型;

(2)HEARD头部,它允许客户端传递关于请求的信息;

(3)CONTENT资源的路径;

(4)DATA数据的可选消息主体。

三、REST接口调用方式?

REST接口调用,一般前端通过异步调用(Ajax)方式,而后端则可以使用多种方式来处理,常见的有以下几种:

1、HttpURLConnection方式

HttpURLConnection是Java的标准类,可用于向指定网站发送GET请求、POST请求。HttpURLConnection是同步请求,因此需放在子线程中,使用实例如下:

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class LogUploader {

    public static void sendLogStream(String log){
        try{
            //请求的的URL
            URL url  =new URL("http://localhost/log");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为post
            conn.setRequestMethod("POST");
            //时间头用来供server进行时钟校对的
            conn.setRequestProperty("clientTime",System.currentTimeMillis() + "");
            //允许上传数据
            conn.setDoOutput(true);
            //设置请求的头信息,设置内容类型为JSON
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            //输出流
            OutputStream out = conn.getOutputStream();
            out.write(("log="+log).getBytes());    //提交数据
            out.flush();
            out.close();
            int code = conn.getResponseCode();
            System.out.println(code);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

2、HttpClient方式(常用)

public static String doPost( byte[] fileBytes, String fileName) {
	//拿到fileName拼接URL
	StringBuffer sb=new StringBuffer();
	final String url = sb.append(EmailGradeTask.EMAILGRADETASKUPLOADURL).append(fileName).toString();
    //创建HttpClient实例
	CloseableHttpClient httpClient = HttpClients.createDefault();
	//创建post方法连接实例,在post方法中传入待连接地址
	HttpPost httpPost = new HttpPost(url);
	CloseableHttpResponse response = null;
	try {
	//设置请求参数(类似html页面中name属性)
		MultipartEntityBuilder entity = MultipartEntityBuilder.create();
		entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		entity.setCharset(Charset.forName("UTF-8"));
		if(fileBytes!=null) {
		//内容类型,用于定义网络文件的类型和网页的编码,决定文件接收方将以什么形式、什么编码读取这个文件
			ContentType OCTEC_STREAM = ContentType.create("application/octet-stream", Charset.forName("UTF-8"));
			//添加文件
			entity.addBinaryBody("file", fileBytes, OCTEC_STREAM, fileName);
		}
		httpPost.setEntity(entity.build());
		//发起请求,并返回请求响应
		response = httpClient.execute(httpPost);
		String uploadResult = EntityUtils.toString(response.getEntity(), "utf-8");
		System.out.println(uploadResult);
		return uploadResult;
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			response.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return "文件上传错误";
}

3、Spring/Springboot的RestTemplate方式(方便)

//请求地址
String url = "http://localhost:8080/testPost";
//入参
RequestBean requestBean = new RequestBean();
requestBean.setTest1("1");
requestBean.setTest2("2");
requestBean.setTest3("3");

RestTemplate restTemplate = new RestTemplate();
ResponseBean responseBean = restTemplate.postForObject(url,requestBean,ResponseBean.class);

Boolean forObject = restTemplate.getForObject(USERSERVICE_URL + "/clean", boolean.class, (Object) null);

User user = restTemplate.getForObject(USERSERVICE_URL+"/{username}/{password}",User.class,params);
                

四、代码实践

https://github.com/XinCongming/rest_ui

https://github.com/XinCongming/rest

发布了77 篇原创文章 · 获赞 19 · 访问量 4052

猜你喜欢

转载自blog.csdn.net/qq_41861558/article/details/103591798