ApiPost7使用介绍 | HTTP && Websocket

一、基本介绍

创建项目(团队下面可以创建多个项目节点,每个项目可以创建多个接口):

参数描述库(填写参数时自动填充描述):

新建环境(前置URL、环境变量很有用):

二、HTTP接口介绍

设计接口(后台设计一个接口,比如:名称、接口后段内容、说明、请求参数、响应值):

请求参数包含Headers(请求头) + Body(raw(json) + formData(表单形式)):

Headers:

Body(json):

Body(form data):


分享(外网或内网链接):

后台提供的接口文档:


调试接口(前端人员对接口的传参、结果的一致性进行调试):

三、Websocket接口介绍

调试接口(未设计任何接口内容):

调试接口(需要用户名+密码两个请求参数):

四、自动化测试

新建测试用例(对设计好的接口+测试条件进行测试,一定要保存 ):

查看测试报告:

五、代码

HTTP

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace UnityFramework.Runtime
{
    /// <summary>
    /// 以文件流形式作为HttpContent
    /// 需要进度值使用本Content,否则使用StreamContent
    /// </summary>
    public class StreamProgressContent : HttpContent
    {
        private const int defaultBufferSize = 4096;

        // 如果FileStream不适合作为流的父类或者本身,使用Stream
        private readonly FileStream content;
        private readonly int bufferSize;
        // 进度回调  已上传字节数 - 总字节数
        private readonly Action<long, long> progressCallback;

        public StreamProgressContent(FileStream content, Action<long, long> progressCallback)
            : this(content, defaultBufferSize, progressCallback)
        {
        }

        public StreamProgressContent(FileStream content, int bufferSize, Action<long, long> progressCallback)
        {
            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferSize));
            }

            this.content = content ?? throw new ArgumentNullException(nameof(content));
            this.bufferSize = bufferSize;
            this.progressCallback = progressCallback ?? throw new ArgumentNullException(nameof(progressCallback));

            Headers.ContentLength = content.Length;
        }

        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            var buffer = new byte[bufferSize];
            var uploadedBytes = 0L;

            using (content)
            {
                while (true)
                {
                    int bytesRead = await content.ReadAsync(buffer, 0, bufferSize);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    await stream.WriteAsync(buffer, 0, bytesRead);

                    uploadedBytes += bytesRead;
                    progressCallback?.Invoke(uploadedBytes, content.Length);
                }
            }
        }

        protected override bool TryComputeLength(out long length)
        {
            length = content.Length;
            return true;
        }
    }
}

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace UnityFramework.Runtime
{
    /// <summary>
    /// 接口确认
    /// 1.POST or GET
    /// 2.json or form or stream(File)
    /// 3.return 
    /// </summary>
    public static class HttpManager
    {
        /*
         * Native:UnityWebRequest
         * NoNative:HttpWebRequest/HttpClient
         */
        
        /// <summary>
        /// [√] 以JSON方式上传数据
        /// </summary>
        /// <param name="uri">接口地址</param>
        /// <param name="data">json数据</param>
        /// <returns>接口返回</returns>
        public static string PostData(string uri, string data)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                req.Method = "POST";
                req.Timeout = 5000;
                req.ContentType = "application/json";
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                req.ContentLength = bytes.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bytes, 0, bytes.Length);
                    reqStream.Close();
                }

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();

                if (stream != null)
                {
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string result = reader.ReadToEnd();
                    Debug.Log($"Json方式(Http)上传返回:{result}");

                    return result;
                }
            }
            catch (Exception ex)
            {
                Debug.Log($"[Post data failed]\n{ex.Message}");
            }

            return string.Empty;
        }

        /// <summary>
        /// [√] 以表单方式上传数据
        /// 此方式是Unity API,表单仅能添加Field(int/string)和BinaryData,二进制数据不等于stream
        /// </summary>
        /// <param name="uri">接口地址</param>
        /// <param name="formData">表单数据</param>
        /// <returns>接口返回</returns>
        public static async UniTask<string> PostFormDataNative(string uri, WWWForm formData)
        {
            // 注:还可以用UnityWebRequest.PostWwwForm
            UnityWebRequest unityWebRequest = UnityWebRequest.Post(uri, formData);
            await unityWebRequest.SendWebRequest();

            if (!string.IsNullOrEmpty(unityWebRequest.error))
            {
                Debug.Log($"[POST form data native failed]\n{unityWebRequest.error}");
                return string.Empty;
            }

            string result = unityWebRequest.downloadHandler.text;
            Debug.Log($"表单方式(Unity)上传返回:{result}");
            unityWebRequest.Dispose();

            return result;
        }

        /// <summary>
        /// [√] 以表单方式上传数据
        /// 此方式是Http API,表单不仅可添加string/bytes/stream,还有继承HttpContent的可计算上传进度值的StreamContent
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="formData"></param>
        /// <returns></returns>
        public static async UniTask<string> PostFormData(string uri, MultipartFormDataContent formData)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    // // MultipartFormDataContent示例
                    // var formData = new MultipartFormDataContent();
                    // // 添加string content
                    // formData.Add(new StringContent("contentValue", Encoding.UTF8), "key");
                    // // 添加stream content(不带progress)
                    // formData.Add(new StreamContent(null), "key", "fileName");
                    // // 添加stream content(带progress)
                    // formData.Add(new StreamProgressContent(null, 4096, null));

                    var response = await client.PostAsync(uri, formData);
                    if (response.IsSuccessStatusCode)
                    {
                        string result = await response.Content.ReadAsStringAsync();
                        Debug.Log($"表单方式(Http)上传返回:{result}");
                        return result;
                    }
                    
                    Debug.Log($"[Post form data failed]");
                    return string.Empty;
                }
            }
            catch (Exception e)
            {
                Debug.Log($"[Post form data failed]\n{e}");
                return string.Empty;
            }
        }
    }
}

Websocket

相关推荐
hzyyyyyyyu6 小时前
隧道技术-tcp封装icmp出网
网络·网络协议·tcp/ip
清尘沐歌9 小时前
有什么好用的 WebSocket 测试工具吗?
websocket·网络协议·测试工具
清尘沐歌9 小时前
有什么好用的 WebSocket 调试工具吗?
网络·websocket·网络协议
earthzhang202110 小时前
《深入浅出HTTPS》读书笔记(7):安全的密码学Hash算法
网络·网络协议·http·https·1024程序员节
杜杜的man10 小时前
【go从零单排】HTTP客户端和服务端
开发语言·http·golang
AI原吾10 小时前
探索 Python HTTP 的瑞士军刀:Requests 库
开发语言·python·http·requests
找藉口是失败者的习惯10 小时前
探索 HTTP 请求方法:GET、POST、PUT、DELETE 等的用法详解
网络·网络协议·http
vortex510 小时前
HTTP 协议及内外网划分详解
网络·网络协议·http·网络安全
莫轻言舞10 小时前
Java Http 接口对接太繁琐?试试 UniHttp 框架吧
网络·网络协议·http
流氓也是种气质 _Cookie10 小时前
鸿蒙HarmonyOS 网络请求获取数据Http
http·鸿蒙·鸿蒙系统