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協議與先後端聯調

相關文章
相關標籤/搜索