【Unity】UnityWebRequest学习——Unity中的HTTP网络通信

UnityWebRequest 简介

Unity中的HTTP通信主要依赖的是Unity自带的UnityWebRequest类。UnityWebRequest 提供了一个模块化系统,用于构成 HTTP 请求和处理 HTTP 响应。

UnityWebRequest 生态系统将 HTTP 事务分解为三个不同的操作:

  • 向服务器提供数据
  • 从服务器接收数据
  • HTTP 流量控制(例如,重定向和错误处理)

对于任何 HTTP 事务,正常的代码流程如下:

  1. 创建 Web 请求对象
  2. 配置 Web 请求对象
    2.1 设置自定义标头
    2.2 设置 HTTP 动词(例如 GET、POST 和 HEAD - 除 Android 之外的所有平台都允许使用自定义动词)
    2.3 设置 URL *(可选)创建上传处理程序并将其附加到 Web 请求
    2.4 提供要上传的数据
    2.5 提供要上传的 HTTP 表单 *(可选)创建下载处理程序并将其附加到 Web 请求
  3. 发送 Web 请求
    如果在协程中,可获得 Send() 调用的结果以等待请求完成 (可选)读取从下载处理程序接收的数据 (可选)从 UnityWebRequest 对象中读取错误信息、HTTP 状态码和响应标头

HTTP网络通信流程

HTTP是基于客户端/服务端(C/S)的架构模型,通过一个可靠的链接来交换信息,是一个无状态的请求/响应协议。浏览器作为 HTTP 客户端通过 URL 向 HTTP 服务端即 WEB 服务器发送所有请求。Web 服务器根据接收到的请求后,向客户端发送响应信息。
HTTP 默认端口号为 80,但是也可以改为 8080 或者其他端口。

HTTP 三点注意事项

  • HTTP 是无连接的:即限制每次连接只处理一个请求,服务器处理完客户的请求,并收到客户的应答后,即断开连接,采用这种方式可以节省传输时间。

  • HTTP 是媒体独立的:只要客户端和服务器知道如何处理的数据内容,任何类型的数据都可以通过HTTP发送,客户端以及服务器指定使用适合的 MIME-type 内容类型。

  • HTTP 是无状态的:HTTP 协议是无状态协议,无状态是指协议对于事务处理没有记忆能力,缺少状态意味着如果后续处理需要前面的信息,则它必须重传,这样可能导致每次连接传送的数据量增大,另一方面,在服务器不需要先前信息时它的应答就较快。

HTTP请求

客户端发送一个HTTP请求到服务器的请求消息包括以下格式:
请求行(request line)、请求头部(header)、空行和请求数据四个部分组成。
在这里插入图片描述

HTTP响应

HTTP响应也由四个部分组成,分别是:状态行、消息报头、空行和响应正文。
在这里插入图片描述

例子

使用Unity内置的UnityWebRequest类进行HTTP请求(GET)

使用UnityWebRequest.Get(url)来获取对应的信息。例子中请求了https://www.baidu.com这一URL对应的资源,返回的数据是一个html文件的文本内容。

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class UnityPageRequest : MonoBehaviour
{
    
    
    IEnumerator Start()
    {
    
    
        var url = "https://www.baidu.com";
        var www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        if (www.isHttpError || www.isNetworkError)
        {
    
    
            Debug.Log(www.responseCode);
            Debug.Log(www.error);
        }
        else
        {
    
    
            Debug.Log(www.responseCode); //状态码 200表示请求成功
            Debug.Log(www.downloadHandler.text); //服务器响应信息
        }
    }
}

得到的服务器响应信息:

<html>
<head>
	<script>
		location.replace(location.href.replace("https://","http://"));
	</script>
</head>
<body>
	<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>

使用BestHTTP插件进行HTTP请求(GET)

把目标Url作为构造参数创建 HTTPRequest类实例,并调用Send()即可。注意在使用时需要引用BestHTTP的命名空间。

using UnityEngine;
using BestHTTP;
using System;

public class UnityPageRequest : MonoBehaviour
{
    
    
    private void Start()
    {
    
    
        string str = "https://www.baidu.com";
        new HTTPRequest(new Uri(str), (req, response) => {
    
    
            string text = response.DataAsText; // 服务器响应信息
            Debug.Log(text);
        }).Send();
    }
}

得到的服务器响应信息是同样的:

<html>
<head>
	<script>
		location.replace(location.href.replace("https://","http://"));
	</script>
</head>
<body>
	<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>

上述两个例子都是使用GET来传递数据的实例。HTTP还有其他的请求方法。

使用Unity内置的UnityWebRequest类进行HTTP请求(POST)

使用UnityWebRequest.Post(url,formdata)将表单发送到HTTP服务器。

using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class UnityPageRequest : MonoBehaviour
{
    
    
    IEnumerator Start()
    {
    
    
        //Post请求的地址
        string url = "https://www.baidu.com";
        //Post请求的参数
        WWWForm form = new WWWForm();
        form.AddField("key1", "value1");
        form.AddField("key2", "value2");
        UnityWebRequest webRequest = UnityWebRequest.Post(url, form);
        //发送请求
        yield return webRequest.SendWebRequest();
        if (string.IsNullOrEmpty(webRequest.error))
        {
    
    
            //Post的请求成功
            //Post请求的返回参数
            var data = webRequest.downloadHandler.text;
            Debug.Log(data);
            Debug.Log("成功");
        }
        else
        {
    
    
            //Post的请求失败
            Debug.Log("失败");
        }
    }
}

得到的服务器响应信息:

<!DOCTYPE html>
<!--STATUS OK-->
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <meta content="always" name="referrer">
    <script src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/nocache/imgdata/seErrorRec.js"></script>
    <title>页面不存在_百度搜索</title>
    <style data-for="result">
        body {
      
      color: #333; background: #fff; padding: 0; margin: 0; position: relative; min-width: 700px; font-family: Arial, 'Microsoft YaHei'; font-size: 12px }
        p, form, ol, ul, li, dl, dt, dd, h3 {
      
      margin: 0; padding: 0; list-style: none }
        input {
      
      padding-top: 0; padding-bottom: 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box } img {
      
      border: none; }
        .logo {
      
      width: 117px; height: 38px; cursor: pointer }
         #wrapper {
      
      _zoom: 1 }
        #head {
      
      padding-left: 35px; margin-bottom: 20px; width: 900px }
        .fm {
      
      clear: both; position: relative; z-index: 297 }
        .btn, #more {
      
      font-size: 14px } 
        .s_btn {
      
      width: 95px; height: 32px; padding-top: 2px\9; font-size: 14px; padding: 0; background-color: #ddd; background-position: 0 -48px; border: 0; cursor: pointer }
        .s_btn_h {
      
      background-position: -240px -48px }
        .s_btn_wr {
      
      width: 97px; height: 34px; display: inline-block; background-position: -120px -48px; *position: relative; z-index: 0; vertical-align: top }
        #foot {
      
      }
        #foot span {
      
      color: #666 }
        .s_ipt_wr {
      
      height: 32px }
        .s_form:after, .s_tab:after {
      
      content: "."; display: block; height: 0; clear: both; visibility: hidden }
        .s_form {
      
      zoom: 1; height: 55px; padding: 0 0 0 10px }
        #result_logo {
      
      float: left; margin: 7px 0 0 }
        #result_logo img {
      
      width: 101px }
        #head {
      
      padding: 0; margin: 0; width: 100%; position: absolute; z-index: 301; min-width: 1000px; background: #fff; border-bottom: 1px solid #ebebeb; position: fixed; _position: absolute; -webkit-transform: translateZ(0) }
        #head .head_wrapper {
      
      _width: 1000px }
        #head.s_down {
      
      box-shadow: 0 0 5px #888 }
        .fm {
      
      clear: none; float: left; margin: 11px 0 0 10px }
        #s_tab {
      
      background: #f8f8f8; line-height: 36px; height: 38px; padding: 55px 0 0 121px; float: none; zoom: 1 }
        #s_tab a, #s_tab b {
      
      display: inline-block; text-decoration: none; text-align: center; color: #666; font-size: 14px }
        #s_tab b {
      
      border-bottom: 2px solid #4E6EF2; color: #222 }
        #s_tab a:hover {
      
      color: #323232 }
        #content_left {
      
      width: 540px; padding-left: 149px;padding-top: 2px;}
        .to_tieba, .to_zhidao_bottom {
      
      margin: 10px 0 0 121px }
        #help {
      
      background: #f5f6f5; zoom: 1; padding: 0 0 0 50px; float: right }
        #help a {
      
      color: #9195a3; padding-right: 21px; text-decoration: none }
        #help a:hover {
      
      color: #333 }
        #foot {
      
      position: fixed; bottom:0; width: 100%; background: #f5f6f5; border-top: 1px solid #ebebeb; text-align: left; height: 42px; line-height: 42px; margin-top: 40px; *margin-top: 0; _position:absolute; _bottom:auto; _top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0))); }

        .content_none {
      
      padding: 45px 0 25px 121px } .s_ipt_wr.bg,
        .s_btn_wr.bg, #su.bg {
      
      background-image: none }
        .s_ipt_wr.bg {
      
      background: 0 }
        .s_btn_wr {
      
      width: auto; height: auto; border-bottom: 1px solid transparent; *border-bottom: 0 }
        .s_btn {
      
      width: 100px; height: 34px; color: white; letter-spacing: 1px; background: #3385ff; border-bottom: 1px solid #2d78f4; outline: medium; *border-bottom: 0; -webkit-appearance: none; -webkit-border-radius: 0 }
        .s_btn:hover {
      
      background: #317ef3; border-bottom: 1px solid #2868c8; *border-bottom: 0; box-shadow: 1px 1px 1px #ccc }
        .s_btn:active {
      
      background: #3075dc; box-shadow: inset 1px 1px 3px #2964bb; -webkit-box-shadow: inset 1px 1px 3px #2964bb; -moz-box-shadow: inset 1px 1px 3px #2964bb; -o-box-shadow: inset 1px 1px 3px #2964bb }
        #lg {
      
      display: none }
        #head .headBlock {
      
      margin: -5px 0 6px 121px }
        #content_left .leftBlock {
      
      margin-bottom: 14px; padding-bottom: 5px; border-bottom: 1px solid #f3f3f3 }
        .s_ipt_wr {
      
      border: 1px solid #b6b6b6; border-color: #7b7b7b #b6b6b6 #b6b6b6 #7b7b7b; background: #fff; display: inline-block; vertical-align: top; width: 592px; margin-right: 0; border-right-width: 0; border-color: #b8b8b8 transparent #ccc #b8b8b8; overflow: hidden }
        .s_ipt_wr.ip_short {
      
      width: 439px; }
        .s_ipt_wr:hover, .s_ipt_wr.ipthover {
      
      border-color: #999 transparent #b3b3b3 #999 }
        .s_ipt_wr.iptfocus {
      
      border-color: #4e6ef2 transparent #4e6ef2 #4e6ef2 }
        .s_ipt_tip {
      
      color: #aaa; position: absolute; z-index: -10; font: 16px/22px arial; height: 32px; line-height: 32px; padding-left: 7px; overflow: hidden; width: 526px }
        .s_ipt {
      
      width: 526px; height: 22px; font: 16px/18px arial; line-height: 22px\9; margin: 6px 0 0 7px; padding: 0; background: transparent; border: 0; outline: 0; -webkit-appearance: none }
        #kw {
      
      position: relative;display: inline-block;}
        input::-ms-clear {
      
      display: none }
        /*Error page css*/
        .norsSuggest {
      
      display: inline-block; color: #333; font-family: arial; font-size: 13px; position: relative; } 
        .norsTitle {
      
      font-size: 22px;font-weight: normal; color: #333; margin: 29px 0 25px 0; }
        .norsTitle2 {
      
      font-family: arial; font-size: 13px; color: #666; }
        .norsSuggest ol {
      
      margin-left: 47px; }
        .norsSuggest li {
      
      margin: 13px 0; }
        #content_right {
      
      
    border-left: 1px solid #e1e1e1;
    width: 384px;
    margin-top: 20px;
    float: right;
    padding-left: 17px;
}
#wrapper_wrapper {
      
      
    width: 1235px;
    margin-top: 50px;
}
.cr-content {
      
      
    width: 351px;
    font-size: 13px;
    line-height: 1.54em;
    color: #333;
    margin-top: 8px;
    margin-left: 19px;
    word-wrap: break-word;
    word-break: normal;
}
@media screen and (max-width: 1217px) {
      
      
    #wrapper_wrapper {
      
      
        width: 1002px;
    }
    #wrapper_wrapper #content_right {
      
      
        width: 271px;
    }
    #wrapper_wrapper .cr-content {
      
      
        width: 259px;
    }
}
.opr-toplist-title {
      
      
    position: relative;
    font-size: 14px;
    line-height: 1.29em;
    font-weight: 700;
    margin-bottom: 3px;
    font: 14px/22px Arial,sans-serif;
    color: #222;
    font-weight: 400;
}
.opr-toplist-table {
      
      
    width: 100%;
    border-collapse: collapse;
    border-spacing: 0;
    font-size: 13px;
}
.opr-toplist-table th,td {
      
      
    line-height: 1.54;
    border-bottom: 1px solid #f3f3f3;
    text-align: left;
}
.opr-toplist-table thead th {
      
      
    padding-top: 4px;
    padding-bottom: 4px;
    font-weight: 400;
    color: #666;
    white-space: nowrap;
    background-color: #fafafa;  
}
.opr-toplist-table .opr-toplist-right {
      
      
    text-align: right;
    white-space: nowrap;
}
.opr-toplist-table td {
      
      
    width: 100%;
    font-size: 13px;
    padding-top: 5.5px;
    padding-bottom: 5.5px;
    vertical-align: top;
}
.opr-toplist-table a:hover {
      
      
    color: #315EFB;
    text-decoration: underline;
}
.opr-toplist-table td{
      
      
    padding-top: 5px 0;
    border: none!important;
    height: 20px;
    line-height: 20px!important;
}
.opr-item-text{
      
      
    font: 14px/22px Arial,sans-serif;
    color: #2440B3;
}
.opr-index-item {
      
      
    display: inline-block;
    padding:1px 0;
    color: #9195A3;
    width: 20px;
    height: 16px;
    line-height: 100%;
    font-size: 15px;
    margin-right: 1px;
    text-align: left;
}
.opr-index-hot1 {
      
      
    color: #f54545;
}

.opr-index-hot2 {
      
      
    color: #ff8547;
}
.opr-index-hot3 {
      
      
    color: #ffac38;
}
.opr-item-text {
      
      
    text-decoration: none;  
}
.opr-toplist-info {
      
      
    color: #666;
    text-align: right;
    margin-top: 5px;
}
.opr-toplist-info>a {
      
      
    color: #666;
}
/* 新加 */
@font-face {
      
      
  font-family: 'cIconfont';
  src: url('./font/iconfont.eot');
  src: url('./font/iconfont.eot?#iefix') format('embedded-opentype'),
    url('./font/iconfont.woff2') format('woff2'),
    url('./font/iconfont.woff') format('woff'),
    url('./font/iconfont.ttf') format('truetype'),
    url('./font/iconfont.svg#iconfont') format('svg');
}
.s_form {
      
      
    zoom: 1;
    padding: 15px 0 4px 16px;
    height: 40px;
    font-size: 0;
}
#result_logo{
      
      
    margin-top: 2px;
}
#result_logo img {
      
      
    width: 101px;
    height: 33px;
}
.fm {
      
      
    margin-left: 19px;
}
.s_ipt_wr{
      
      
    box-sizing: border-box;
    height:40px;
    line-height: 40px;
    border: 2px solid #c4c7ce;
    border-radius: 10px 0 0 10px;
    border-right: 0;
    overflow: visible;
}
.s_btn_wr .s_btn{
      
      
    cursor: pointer;
    width: 112px;
    height: 40px;
    line-height: 41px;
    line-height: 40px\9;
    background-color: #4e6ef2;
    border-radius: 0 10px 10px 0;
    font-size: 17px;
    box-shadow: none;
    font-weight: 400;
    border: 0;
    outline: 0;
    letter-spacing: normal;
}
.s_btn_wr .s_btn:hover{
      
      
    background: #4662d9;
}
.s_ipt_wr.ip_short{
      
      
    width: 480px;
}
#kw{
      
      
    width: 465px;
    height: 38px;
    font: 16px/18px arial;
    padding: 10px 0 10px 14px;
    margin: 0;
    background: transparent;
    border: 0;
}
.fm{
      
      
    margin: 0 0 15px 16px;
    clear: none;
    float: left;
    position: relative;
}
#head{
      
      
    border-bottom: none;
    position: relative;
}
#u {
      
      
    height: 40px;
    line-height: 40px;
    padding-right: 30px;
    z-index: 301;
    display: inline-block;
    float: right;
    color: #999;
}
#u .toindex{
      
      
    font-family: Arial, 'Microsoft YaHei';
    font-size: 13px;
    color: #222222;
    text-align: right;
    text-decoration: none;
}
#u .toindex:hover{
      
      
    color: #2640b3;
}
.s-tab-item:hover::before{
      
      
    color: #222 !important;
}
#s_tab {
      
      
    position: absolute;
    left: 0;
    background: none;
    line-height: 36px;
    height: 38px;
    padding: 2px 0 0 150px;
    float: none;
    zoom: 1;
    color: #626675;
    overflow: hidden;
}
#s_tab a, #s_tab b {
      
      
    display: inline-block;
    margin-right: 24px;
    min-width: 44px;
    text-decoration: none;
    font-size: 14px;
    text-align: left;
    line-height: 28px;
    color: #222222;
    font-weight: normal;
}
#s_tab a{
      
      
    color: #626675;
}
#s_tab .s-tab-item:before {
      
      
    display: inline-block;
    margin-right: 2px;
    width: 14px;
    font-family: 'cIconfont'!important;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    background: initial;
    color: #c0c2c8;
}
#s_tab .cur-tab:before {
      
      
    font-family: 'cIconfont'!important;
    color: #626675;
    margin-right: 2px;
    content: '\e608';
}
#s_tab .s-tab-news:before {
      
      
    content: '\e606';
}
#s_tab .s-tab-video:before {
      
      
    content: '\e604';
}
#s_tab .s-tab-pic:before {
      
      
    content: '\e607';
}
#s_tab .s-tab-zhidao:before {
      
      
    content: '\e633';
}
#s_tab .s-tab-wenku:before {
      
      
    content: '\e605';
}
#s_tab .s-tab-tieba:before {
      
      
    content: '\e609';
}
#s_tab .s-tab-map:before {
      
      
    content: '\e630';
}
#s_tab .s-tab-b2b:before {
      
      
    content: '\e603';
}
#content_right{
      
      
    border-left: none;
}
.norsTitle{
      
      
    font-family: Arial, 'Microsoft YaHei';
    font-size: 18px;
    color: #222222;
    text-align: justify;
    line-height: 18px;
}
.norsTitle{
      
      
    margin-bottom: 28px;
}
.norsTitle2{
      
      
    font-family: Arial, 'Microsoft YaHei';
    font-size: 14px;
    color: #333333;
    text-align: justify;
    line-height: 14px;
    margin-bottom: 12px;
}
.norsSuggest a{
      
      
    color: #2440b3;
    text-decoration: none;
}
.norsSuggest a:hover{
      
      
    color: #315efb;
    text-decoration: underline;
}
#foot{
      
      
    background: #f5f5f6;
    color: #9195a3;
    border-top: none;
}
#help{
      
      
    float:left;
    padding-left:150px
}
    </style>
</head>

<body link="#0000cc">
    <div id="wrapper" class="wrapper_l">
        <div id="head">
            <div class="head_wrapper">
                <div class="s_form">
                    <div class="s_form_wrapper">
                        <a href="//www.baidu.com/" id="result_logo"><img src="//www.baidu.com/img/flexible/logo/pc/[email protected]" alt="到百度首页" title="到百度首页"></a>
                        <form id="form" name="f" action="//www.baidu.com/s" class="fm">
                            <input type="hidden" name="ie" value="utf-8">
                            <input type="hidden" name="f" value="8">
                            <input type="hidden" name="rsv_bp" value="1">
                            <input type="hidden" name="ch" value="">
                            <input type="hidden" name="tn" value="baiduerr">
                            <input type="hidden" name="bar" value="">
                            <span class="bg s_ipt_wr iptfocus">
                                <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off" autofocus>
                            </span><span class="bg s_btn_wr">
                                <input type="submit" id="su" value="百度一下" class="bg s_btn">
                            </span>
                        </form>
                    </div>
                    <div id="u">
                        <a class="toindex" href="//www.baidu.com/">百度首页</a>
                    </div>
                </div>
            </div>
        </div>
    <div class="s_tab" id="s_tab">
        <b class="cur-tab">网页</b>
        <a href="//www.baidu.com/?tn=news" class="s-tab-item s-tab-news" wdfield="kw">资讯</a>
        <a href="//v.baidu.com/" class="s-tab-item s-tab-video">视频</a>
        <a href="//image.baidu.com/" class="s-tab-item s-tab-pic">图片</a>
        <a href="//zhidao.baidu.com/" class="s-tab-item s-tab-zhidao">知道</a>
        <a href="//wenku.baidu.com/" class="s-tab-item s-tab-wenku">文库</a>
        <a href="//tieba.baidu.com/index.html" class="s-tab-item s-tab-tieba">贴吧</a>
        <a href="//map.baidu.com/" class="s-tab-item s-tab-map">地图</a>
        <a href="//b2b.baidu.com/s?fr=wwwt" class="s-tab-item s-tab-b2b">采购</a>
        <a href="//www.baidu.com/more/" class="s-tab-item s-tab-more">更多</a>
    </div>
    <div id="wrapper_wrapper">
        <div id="content_left">
            <div class="nors">
                <div class="norsSuggest">
                    <h3 class="norsTitle">很抱歉,您要访问的页面不存在!</h3>
                    <p class="norsTitle2">温馨提示 :</p>
                    <p class="norsTitle2">请检查您访问的网址是否正确</p>
                    <p class="norsTitle2">如果您不能确认访问的网址,请浏览<a href="//www.baidu.com/more/index.html">百度更多</a>页面查看更多网址。</p>
                    <p class="norsTitle2">回到顶部重新发起搜索</p>
                    <p class="norsTitle2">如有任何意见或建议,请及时<a href="http://qingting.baidu.com/index">反馈给我们</a></p>
                </div>
            </div>
        </div>
    </div>
    <div id="foot">
        <span id="help">
            <a href="http://help.baidu.com/question" target="_blank">帮助</a>
            <a href="http://www.baidu.com/search/jubao.html" target="_blank">举报</a>
            <a href="http://jianyi.baidu.com" target="_blank">用户反馈</a>
        </span>
    </div>
</body>
<script>
(function () {
        var LOGURL = 'https://sp1.baidu.com/5b1ZeDe5KgQFm2e88IuM_a/cm.gif';
        var params = 'type=wwwerror&terminal=www';
        var img = new Image();
        img.src = LOGURL + '?' + params;
    })();
    (function () {
        if(window.recommend && window.recommend.query && window.recommend.query.length > 0) {
            var recommendWrapper = document.createElement('div');
            var recommendHtml = '<div <message truncated>

HTTP请求方法

根据HTTP标准,HTTP请求可以使用多种请求方法。

HTTP1.0定义了三种请求方法: GET, POST 和 HEAD方法。
HTTP1.1新增了五种请求方法:OPTIONS, PUT, DELETE, TRACE 和 CONNECT 方法。

方法 描述
GET 请求指定的页面信息,并返回实体主体。
HEAD 类似于 GET 请求,只不过返回的响应中没有具体的内容,用于获取报头。
POST 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST 请求可能会导致新的资源的建立或已有资源的修改。
PUT 从客户端向服务器传送的数据取代指定的文档的内容。
DELETE 请求服务器删除指定的页面。
CONNECT HTTP/1.1 协议中预留给能够将连接改为管道方式的代理服务器。
OPTIONS 允许客户端查看服务器的性能。
TRACE 回显服务器收到的请求,主要用于测试或诊断。
PATCH 是对 PUT 方法的补充,用来对已知资源进行局部更新 。

通常用的比较多的是GET和POST方法。GET一般用来获取信息,POST一般用来向服务器上传信息,比如表单、文件等。

UnityWebRequest类中封装了几种HTTP方法的高级操作:

  • GET对应UnityWebRequest.Get
  • POST对应UnityWebRequest.Post
  • HEAD对应UnityWebRequest.Head
  • PUT对应UnityWebRequest.Put
  • DELETE对应UnityWebRequest.Delete

HTTP状态码

HTTP 状态码的英文为 HTTP Status Code。当用户访问一个网页时,浏览器会向网页所在服务器发出请求。当浏览器接收并显示网页前,此网页所在的服务器会返回一个包含 HTTP 状态码的信息头(server header)用以响应浏览器的请求。

HTTP 状态码由三个十进制数字组成,第一个十进制数字定义了响应的类型。
响应分为五类:信息响应(100–199),成功响应(200–299),重定向(300–399),客户端错误(400–499)和服务器错误 (500–599):

分类 分类描述
1** 信息,服务器收到请求,需要请求者继续执行操作
2** 成功,操作被成功接收并处理
3** 重定向,需要进一步的操作以完成请求
4** 客户端错误,请求包含语法错误或无法完成请求
5** 服务器错误,服务器在处理请求的过程中发生了错误

HTTP状态码列表:

状态码 英文描述 中文描述
100 Continue 继续。客户端应继续其请求
101 Switching Protocols 切换协议。服务器根据客户端的请求切换协议。只能切换到更高级的协议,例如,切换到HTTP的新版本协议
200 OK 请求成功。一般用于GET与POST请求
201 Created 已创建。成功请求并创建了新的资源
202 Accepted 已接受。已经接受请求,但未处理完成
203 Non-Authoritative Information 非授权信息。请求成功。但返回的meta信息不在原始的服务器,而是一个副本
204 No Content 无内容。服务器成功处理,但未返回内容。在未更新网页的情况下,可确保浏览器继续显示当前文档
205 Reset Content 重置内容。服务器处理成功,用户终端(例如:浏览器)应重置文档视图。可通过此返回码清除浏览器的表单域
206 Partial Content 部分内容。服务器成功处理了部分GET请求
300 Multiple Choices 多种选择。请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于用户终端(例如:浏览器)选择
301 Moved Permanently 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。今后任何新的请求都应使用新的URI代替
302 Found 临时移动。与301类似。但资源只是临时被移动。客户端应继续使用原有URI
303 See Other 查看其它地址。与301类似。使用GET和POST请求查看
304 Not Modified 未修改。所请求的资源未修改,服务器返回此状态码时,不会返回任何资源。客户端通常会缓存访问过的资源,通过提供一个头信息指出客户端希望只返回在指定日期之后修改的资源
305 Use Proxy 使用代理。所请求的资源必须通过代理访问
306 Unused 已经被废弃的HTTP状态码
307 Temporary Redirect 临时重定向。与302类似。使用GET请求重定向
400 Bad Request 客户端请求的语法错误,服务器无法理解
401 Unauthorized 请求要求用户的身份认证
402 Payment Required 保留,将来使用
403 Forbidden 服务器理解请求客户端的请求,但是拒绝执行此请求
404 Not Found 服务器无法根据客户端的请求找到资源(网页)。通过此代码,网站设计人员可设置"您所请求的资源无法找到"的个性页面
405 Method Not Allowed 客户端请求中的方法被禁止
406 Not Acceptable 服务器无法根据客户端请求的内容特性完成请求
407 Proxy Authentication Required 请求要求代理的身份认证,与401类似,但请求者应当使用代理进行授权
408 Request Time-out 服务器等待客户端发送的请求时间过长,超时
409 Conflict 服务器完成客户端的 PUT 请求时可能返回此代码,服务器处理请求时发生了冲突
410 Gone 客户端请求的资源已经不存在。410不同于404,如果资源以前有现在被永久删除了可使用410代码,网站设计人员可通过301代码指定资源的新位置
411 Length Required 服务器无法处理客户端发送的不带Content-Length的请求信息
412 Precondition Failed 客户端请求信息的先决条件错误
413 Request Entity Too Large 由于请求的实体过大,服务器无法处理,因此拒绝请求。为防止客户端的连续请求,服务器可能会关闭连接。如果只是服务器暂时无法处理,则会包含一个Retry-After的响应信息
414 Request-URI Too Large 请求的URI过长(URI通常为网址),服务器无法处理
415 Unsupported Media Type 服务器无法处理请求附带的媒体格式
416 Requested range not satisfiable 客户端请求的范围无效
417 Expectation Failed 服务器无法满足Expect的请求头信息
500 Internal Server Error 服务器内部错误,无法完成请求
501 Not Implemented 服务器不支持请求的功能,无法完成请求
502 Bad Gateway 作为网关或者代理工作的服务器尝试执行请求时,从远程服务器接收到了一个无效的响应
503 Service Unavailable 由于超载或系统维护,服务器暂时的无法处理客户端的请求。延时的长度可包含在服务器的Retry-After头信息中
504 Gateway Time-out 充当网关或代理的服务器,未及时从远端服务器获取请求
505 HTTP Version not supported 服务器不支持请求的HTTP协议的版本,无法完成处理

在Unity中可以使用以下代码获取状态码:

var www = UnityWebRequest.Get(url);
Debug.Log(www.responseCode);

URL的编码解码

URL中有一些符号是不能被解析的,所以我们需要进行编码。如 = 这个等号一般是有特殊意义的,编码后变成%3d,就可以被正确读取。
编码:

UnityWebRequest.EscapeURL(string url);
UnityWebRequest.EscapeURL(string url,Encoding e);

解码:

UnityWebRequest.UnEscapeURL(string url);
UnityWebRequest.UnEscapeURL(string url,Encoding e);

猜你喜欢

转载自blog.csdn.net/qq_41084756/article/details/128188592