UnityWebRequest

作者:追风剑情 发布于:2019-12-12 16:43 分类:Unity3d

示例一:上传视频


/// <summary>
/// 上传视频
/// </summary>
/// <param name="url">上传视频地址</param>
/// <param name="bytes">视频文件内容</param>
/// <returns></returns>
IEnumerator UpLoadVideo(string url, byte[] bytes)
{
	yield return null;
	WWWForm form = new WWWForm();
	form.AddField("id", 123);
	form.AddBinaryData("file", bytes, "my_video.mp4", "video/mp4");

	//byte[] bodyRaw = Encoding.UTF8.GetBytes(postDataString);//发送原始数据(即,数据不组织成表单)
        //UnityWebRequest request = new UnityWebRequest(url, "POST");
	UnityWebRequest request = UnityWebRequest.Post(url, form);
        request.timeout = 5;
        //https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest-useHttpContinue.html
        //true:  包含Expect: 100-Continue请求头, http会提前返回,这会导至后面的isNetworkError=true, responseCode=100
        //false: 确保http请求完毕后再返回
        request.useHttpContinue = false;
        request.chunkedTransfer = false; //false:不希望服务器分块返回数据
        request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        //如果不指定post表单,需要这样上传原始数据
        //request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        //request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
	//加上yield return 直到请求完成程序才会继续往下执行
	//yield return request.SendWebRequest();

	//调用后会立即返回,程序继续往下执行
	request.SendWebRequest();

	while (!request.isDone)
	{
		Debug.Log("上传进度: " + request.uploadProgress);
		yield return new WaitForSeconds(0.1f);
	}

	if (request.isHttpError || request.isNetworkError || request.responseCode != 200)
	{
		Debug.LogErrorFormat("上传视频出错\n{0}", request.error);
		yield break; //跳出协程
	}

	Debug.Log("上传视频成功!");
}

    // Post原始数据(即,非表单)
    private IEnumerator PostRaw(string url, string postData, Action successCallback=null, Action failureCallback=null)
    {
        yield return null;
        byte[] bodyRaw = Encoding.UTF8.GetBytes(postData);
        UnityWebRequest request = new UnityWebRequest(url, "POST");
        request.timeout = 10; //单位:秒
        request.useHttpContinue = false; //false:直接上传post数据,不需要发送前征询服务器情况
        request.chunkedTransfer = false; //false:不希望服务器分块返回数据
        request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        //如果不指定post表单,需要这样上传原始数据
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        yield return request.SendWebRequest();

        if (request.isHttpError || request.isNetworkError || request.responseCode != 200)
        {
            Debug.LogErrorFormat("Post Failure\n{0}", request.error);
            if (failureCallback != null)
                failureCallback();
            yield break; //跳出协程
        }

        string json = request.downloadHandler.text;
        if (successCallback != null)
            successCallback(json);
    }


标签: Unity3d

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号