HTTP协议与前后端联调

11 篇文章 0 订阅
9 篇文章 0 订阅

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

介绍

  在前后端分离的开发场景下,不可避免的会有前后端联调。在联调阶段,经常会遇到各式各样的问题,比如乱码问题、前端传的数据(字符串、数组、Json对象)后端无法正常解析等问题。
  本文希望从源头着手,理清问题的根本原因,快速定位出现问题的位置,让前后端联调得心应手,让甩锅不再那么容易……

HTTP协议

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

1. 简介

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

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

2. HTTP method

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

这里写图片描述

说明:
1. 我们常用的一般为get于post。
2. 是否包含主体的意思为请求内容是否带主体。例如,在get方式下由于不带主体,只能使用url的方式传参。

3. Content-type

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

常见的Content-Type:

类型说明
text/htmlhtml类型
text/csscss文件
text/javascriptjs文件
text/plain文本文件
application/jsonjson类型
application/xmlxml类型
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]可见。

相关资料:
1. Content-type对照表:http://tool.oschina.net/commons
2. Form content types:https://www.w3.org/TR/html4/interact/forms.html#h-17.13.4
3. 字符解码时加号解码为空格问题探究:http://muchstudy.com/2017/12/06/字符解码时加号解码为空格问题探究/
4. 理解HTTP之Content-Type:http://homeway.me/2015/07/19/understand-http-about-content-type/

4. 字符集与编码

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

一图胜千言:

这里写图片描述

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

相关资料:
1. 字符集列表:https://www.iana.org/assignments/character-sets/character-sets.xhtml
2. 字符编码详解:http://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:https://xhr.spec.whatwg.org/
2. Fetch Standard:https://fetch.spec.whatwg.org/
3. XMLHttpRequest介绍:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
4. fetch介绍:https://developers.google.com/web/updates/2015/03/introduction-to-fetch
5. fetch 简介: 新一代 Ajax API: https://juejin.im/entry/574512b7c26a38006c43567c
6. axios源码:https://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的本质是什么,它是如何工作的?:https://www.zhihu.com/question/21416727
2. tomcat是如何处理http请求的?:https://blog.csdn.net/qq_38182963/article/details/78660777

结果汇总

请求方式method请求Content-Type数据格式后端收到的Content-Type能否通过getParameter获取数据能否通过inputStream获取数据后端接收类型
XHRGet未设置url传参null键值对
XHRPost未设置json字符串text/plain;charset=UTF-8字符串
XHRPost未设置a=1&b=2格式字符串text/plain;charset=UTF-8字符串
XHRPostapplication/x-www-form-urlencodeda=1&b=2格式字符串application/x-www-form-urlencoded后端收到key为a和b,值为1和2的键值对
XHRPostapplication/x-www-form-urlencodedjson字符串application/x-www-form-urlencoded后端收到一个key为json数据,值为空的键值对
axiosGet未设置url传参null键值对
axiosPost未设置json对象application/json;charset=UTF-8json字符串
axiosPost未设置数组application/json;charset=UTF-8数组字符串
axiosPost未设置a=1&b=2格式字符串application/x-www-form-urlencoded键值对
fetchGet未设置url传参null键值对
fetchPost未设置a=1&b=2格式字符串text/plain;charset=UTF-8a=1&b=2字符串
fetchPost未设置json对象text/plain;charset=UTF-8后端收到[object Object]字符串
fetchPostapplication/x-www-form-urlencoded;charset=UTF-8a=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-dataContent-Type: multipart/form-dataform表单的附件提交方式
x-www-form-urlencodedContent-Type: application/x-www-form-urlencodedform表单的post提交方式
rawContent-Type: text/plain;charset=UTF-8文本的提交方式
  • 2
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值