#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;
}