HTTP协议与先后端联调

介绍

  在先后端分离的开发场景下,不可避免的会有先后端联调。在联调阶段,常常会遇到各式各样的问题,好比乱码问题、前端传的数据(字符串、数组、Json对象)后端没法正常解析等问题。
  本文但愿从源头着手,理清问题的根本缘由,快速定位出现问题的位置,让先后端联调驾轻就熟,让甩锅再也不那么容易......javascript

HTTP协议

  之因此这里会介绍一下HTTP协议,是由于先后端联调离不开HTTP。了解了HTTP协议,有助于更好的理解数据传输的流程,以及更好的分析出究竟是在哪一个环节出了问题,方便排查。css

1. 简介

  首先,http是一个无状态的协议,即每次客户端和服务端交互都是无状态的,一般使用cookie来保持状态。
  下图为http请求与响应的大体结构(本部分配图均来自于《HTTP权威指南》):html

说明:
  从上图中能够看出,HTTP请求大体分为三个部分:起始行、首部、主体。在请求起始行里,表面了请求方法、请求地址以及http协议的版本。另外,首部便是咱们常说的http header。前端

2. HTTP method

  下面是经常使用的HTTP请求方法以及介绍: java

说明:jquery

  1. 咱们经常使用的通常为get于post。
  2. 是否包含主体的意思为请求内容是否带主体。例如,在get方式下因为不带主体,只能使用url的方式传参。

3. Content-type

  HTTP传输的内容类型与编码是由Content-Type来控制的,客户端与服务端经过它来识别与解析传输内容。ios

常见的Content-Type:git

类型 说明
text/html html类型
text/css css文件
text/javascript js文件
text/plain 文本文件
application/json json类型
application/xml xml类型
application/x-www-form-urlencoded 表单,表单提交时的默认类型
multipart/form-data 附件类型,通常为表单文件上传

  前面六个为常见的文件类型,后面两个为表单数据提交时类型。咱们ajax提交数据时通常为Content-Type:application/x-www-form-urlencoded;charset=utf-8,以此声明了本次请求的数据格式与数据编码方式。须要额外说明的是,application/x-www-form-urlencoded此种类型比较特殊,数据发送时会把表单数据拼接成相似于a=1&b=2&c=3的格式,若是数据中存在空格或特殊字符,会进行转换,标准文档在这里,更详细的在[RFC1738]可见。github

相关资料:web

  1. Content-type对照表:tool.oschina.net/commons
  2. Form content types:www.w3.org/TR/html4/in…
  3. 字符解码时加号解码为空格问题探究:muchstudy.com/2017/12/06/…
  4. 理解HTTP之Content-Type:homeway.me/2015/07/19/…

4. 字符集与编码

  先后端联调之因此须要了解这部分,是由于在先后端的数据交互中,常常会碰到乱码的问题,了解了这块内容,对于解决乱码问题就手到擒来了。

一图胜千言:

  在图中,charset的值为iso-8859-6,详细介绍了一个文字从编码到解码,再到显示的完整过程。

相关资料:

  1. 字符集列表:www.iana.org/assignments…
  2. 字符编码详解:muchstudy.com/2016/08/26/…

前端部分

  前端部分负责发起HTTP请求,前端经常使用的HTTP请求工具类有jqueryaxiosfetch。实际上jquery与axios的底层都是使用XMLHttpRequest来发起http请求的,fetch属于浏览器内置的发起http请求方法。

前端ajax请求样例:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.5.1/qs.min.js"></script>
<title>前端发起HTTP请求样例</title>
</head>
<body>
	<h2>使用XMLHttpRequest</h2>
	<button onclick="xhrGet()">XHR Get</button>
	<button onclick="xhrPost()">XHR Post</button>
	<h2>使用axios</h2>
	<button onclick="axiosGet()">Axios Get</button>
	<button onclick="axiosPost()">Axios Post</button>
	<h2>使用fetch</h2>
	<button onclick="fetchGet()">Fetch Get</button>
	<button onclick="fetchPost()">Fetch Post</button>
	<script> // 封装XMLHttpRequest发起ajax请求 let Axios = function({url, method, data}) { return new Promise((resolve, reject) => { var xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.onreadystatechange = function() { // readyState == 4说明请求已完成 if (xhr.readyState == 4 && xhr.status == 200) { // 从服务器得到数据 resolve(xhr.responseText) } }; if(data){ xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8'); xhr.send(Qs.stringify(data)); //xhr.send("a=1&b=2"); //xhr.send(JSON.stringify(data)); }else{ xhr.send(); } }) } // 须要post提交的数据 let postData = { firstName: 'Fred', lastName: 'Flintstone', fullName: '姓 名', arr:[1,2,3] } // 请求地址 let url = 'DemoServlet'; function xhrGet(){ Axios({ url: url+'?a=1', method: 'GET' }).then(function (response) { console.log(response); }) } function xhrPost(){ Axios({ url: url, method: 'POST', data: postData }).then(function (response) { console.log(response); }) } function axiosGet(){ // 默认Content-Type = null axios.get(url, { params: { ID: '12345' } }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); } function axiosPost(){ // 默认Content-Type = application/json;charset=UTF-8 axios.post(url, postData).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); // 默认Content-Type = application/x-www-form-urlencoded axios({ method: 'post', url: url, data: Qs.stringify(postData) }).then(function (response) { console.log(response); }); } function fetchGet(){ fetch(url+'?id=1').then(res => res.text()).then(data => { console.log(data) }) } function fetchPost(){ fetch(url, { method: 'post', body: postData }) .then(res => res.text()) .then(function (data) { console.log(data); }) .catch(function (error) { console.log('Request failed', error); }); } </script>
</body>
</html>

复制代码

相关资料:

  1. XMLHttpRequest Standard:xhr.spec.whatwg.org/
  2. Fetch Standard:fetch.spec.whatwg.org/
  3. XMLHttpRequest介绍:developer.mozilla.org/zh-CN/docs/…
  4. fetch介绍:developers.google.com/web/updates…
  5. fetch 简介: 新一代 Ajax API: juejin.im/entry/57451…
  6. axios源码:github.com/axios/axios

后端部分

  这里使用Java平台为样例来介绍后端是如何接收HTTP请求的。在J2EE体系下,数据的接收与返回实际上都是经过Servlet来完成的。

Servlet接收与返回数据样例:

package com.demo.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DemoServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("-----------------start----------------");
		System.out.println("Content-Type:" + request.getContentType());
		// 打印请求参数
		System.out.println("=========请求参数========");
		Enumeration<String> em = request.getParameterNames();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			System.out.println(name + " = " + value);
			response.getWriter().append(name + " = " + value);
		}
		// 从inputStream中获取
		System.out.println("===========inputStream===========");
		StringBuffer sb = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null)
				sb.append(line);
		} catch (Exception e) {
			/* report an error */
		}
		System.out.println(sb.toString());
		System.out.println("-----------------end----------------");
		response.getWriter().append(sb.toString());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
复制代码

相关资料:

  1. servlet的本质是什么,它是如何工做的?:www.zhihu.com/question/21…
  2. tomcat是如何处理http请求的?:blog.csdn.net/qq_38182963…

结果汇总

请求方式 method 请求Content-Type 数据格式 后端收到的Content-Type 可否经过getParameter获取数据 可否经过inputStream获取数据 后端接收类型
XHR Get 未设置 url传参 null 键值对
XHR Post 未设置 json字符串 text/plain;charset=UTF-8 字符串
XHR Post 未设置 a=1&b=2格式字符串 text/plain;charset=UTF-8 字符串
XHR Post application/x-www-form-urlencoded a=1&b=2格式字符串 application/x-www-form-urlencoded 后端收到key为a和b,值为1和2的键值对
XHR Post application/x-www-form-urlencoded json字符串 application/x-www-form-urlencoded 后端收到一个key为json数据,值为空的键值对
axios Get 未设置 url传参 null 键值对
axios Post 未设置 json对象 application/json;charset=UTF-8 json字符串
axios Post 未设置 数组 application/json;charset=UTF-8 数组字符串
axios Post 未设置 a=1&b=2格式字符串 application/x-www-form-urlencoded 键值对
fetch Get 未设置 url传参 null 键值对
fetch Post 未设置 a=1&b=2格式字符串 text/plain;charset=UTF-8 a=1&b=2字符串
fetch Post 未设置 json对象 text/plain;charset=UTF-8 后端收到[object Object]字符串
fetch Post application/x-www-form-urlencoded;charset=UTF-8 a=1&b=2格式字符串 application/x-www-form-urlencoded;charset=UTF-8 键值对
表格可横向滚动

  经过上面的表格内容能够发现,凡是使用get或者content-type为application/x-www-form-urlencoded发送数据,在后端servlet都会默认把数据转换为键值对。不然,须要从输入流中获取前端发送过来的字符串数据,再使用fastJSON等后端工具类转换为Java实体类或集合对象。

联调工具Postman

  能够在chrome的应用商店中下载Postman插件,在浏览器中模拟HTTP请求。Postman的界面以下:

说明:

  1. 发送get请求直接在url上带上参数,接着点击send便可
  2. 发送post请求,数据有三种传输方式;form-datax-www-form-urlencodedraw(未经加工的)
类型 Content-Type 说明
form-data Content-Type: multipart/form-data form表单的附件提交方式
x-www-form-urlencoded Content-Type: application/x-www-form-urlencoded form表单的post提交方式
raw Content-Type: text/plain;charset=UTF-8 文本的提交方式

原文地址:HTTP协议与先后端联调

相关文章
相关标签/搜索