Unity 进行 multipart/form-data 请求

#Unity学习笔记#

对于这类请求:

参数是一个字符串和一个图片文件

multipart/form-data 请求体标准格式:

--Boundary
Content-Disposition: form-data; name="field1"

value1
--Boundary
Content-Disposition: form-data; name="field2"; filename="file1.txt"
Content-Type: text/plain

...文件内容...
--Boundary
Content-Disposition: form-data; name="field3"

value3
--Boundary--

网络请求:


        UnityWebRequest webRequest = new ()
        {
            url = $"***************",
            method = "POST"
        };
        string boundary = "----WebKitFormBoundary7MASKDMkm240gW";
        webRequest.SetRequestHeader("Content-Type", $"multipart/form-data; boundary={boundary}");

        webRequest.uploadHandler = new UploadHandlerRaw(BodyBuilder(img, boundary));
        yield return webRequest.SendWebRequest();
        if (webRequest.error == null && webRequest.isDone)
        {
        }
        else
        {
            Debug.Log("发送信息失败,获取失败!" + webRequest.error);
        }
        webRequest.Dispose();

multipart/form-data 请求体:


    byte[] BodyBuilder(byte[] img, string boundary)
    {
        string crlf = "\r\n";
        // 构建请求体
        StringBuilder bodyBuilder = new StringBuilder();
        bodyBuilder.Append("--" + boundary + crlf);
        bodyBuilder.Append("Content-Disposition: form-data; name=\"path\"" + crlf);
        bodyBuilder.Append(crlf);
        bodyBuilder.Append(path + crlf);
        bodyBuilder.Append($"--" + boundary + crlf);
        bodyBuilder.Append($"Content-Disposition: form-data; name=\"file\"; filename=\"post.png\"" + crlf);
        bodyBuilder.Append("Content-Type: image/png" + crlf);
        bodyBuilder.Append(crlf);
        byte[] bodyTextPart = Encoding.UTF8.GetBytes(bodyBuilder.ToString());
        byte[] imageData = img;//图片字节
        long fullRequestBodyLength = bodyTextPart.Length + imageData.Length + System.Text.Encoding.UTF8.GetBytes(crlf + "--" + boundary + "--" + crlf).Length;
        byte[] fullRequestBody = new byte[fullRequestBodyLength];
        Array.Copy(bodyTextPart, fullRequestBody, bodyTextPart.Length);
        int imageDataOffset = bodyTextPart.Length;
        Array.Copy(imageData, 0, fullRequestBody, imageDataOffset, imageData.Length);
        Array.Copy(System.Text.Encoding.UTF8.GetBytes(crlf + "--" + boundary + "--" + crlf), 0, fullRequestBody, imageDataOffset + imageData.Length, System.Text.Encoding.UTF8.GetBytes(crlf + "--" + boundary + "--" + crlf).Length);
        return fullRequestBody;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值