Unity HTTP Post 发送数据

将Post请求方式整合到Http通用类中进行调用,代码如下:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System;
using UnityEngine;
public class WebManager {
	/// <summary>
	/// 提交Json数据
	/// </summary>
	/// <param name="url">接口地址</param>
	/// <param name="jsonData">json数据字符串</param>
	/// <param name="success">成功回调</param>
	/// <param name="error">错误回调</param>
	internal void PostJsonData(string url, string jsonData, Action<string> success = null, Action<string> error = null)
	{
		HttpWebRequest request = null;// 声明一个HttpWebRequest请求
		Stream reqstream = null;//获取一个请求流
		HttpWebResponse response = null; //接收返回来的数据
		Stream streamReceive = null;//获取响应流

		try
		{
			byte[] bytes = Encoding.UTF8.GetBytes(jsonData);//将参数字符串转换成字节数组。

			/* HttpWebRequest*/
			request = (HttpWebRequest)WebRequest.Create(url);// 声明一个HttpWebRequest请求
			request.Method = "POST";///设置请求模式
			request.KeepAlive = true;
			request.ContentLength = bytes.Length;//设置请求内容大小,当然就设置成我们的参数字节数据大小。
			request.ContentType = "application/json;charset=UTF-8";//设置ContntType("application/json;charset=UTF-8") ,这句很重要,否则无法传递参数ContntType(""text/xml")
			//request.Headers.Add("access_token", access_token);
            //request.Headers.Add("uuid", uuid);
            //request.Headers.Add("os", "u3d");

			/* Stream*/
			reqstream = request.GetRequestStream();//  //发送post的请求,获取请求流
			reqstream.Write(bytes, 0, bytes.Length);// 将参数字节数组写入到请求流里
			reqstream.Close(); 
			request.Timeout = 90000; //设置连接超时时间
			request.Headers.Set("paramaters", "no-cache");//paramaters就是服务接口函数的参数名//接收返回来的数据

			/*HttpWebResponse*/
			response = (HttpWebResponse)request.GetResponse(); //执行请求,获取响应对象

			/* Stream*/
			streamReceive = response.GetResponseStream();//获取响应流
			Encoding encoding = Encoding.UTF8; StreamReader streamReader = new StreamReader(streamReceive, encoding);//创建流读取对象
			string strResult = streamReader.ReadToEnd();// 读取响应流
                                                            // response.Close();
                                                            //streamReceive.Dispose();关闭响应流
			streamReceive.Close();
			streamReader.Dispose();

			success?.Invoke(strResult);
		}
		catch (WebException e)
		{
			// return string.Empty;
			WebResponse wr = e.Response;
			using (StreamReader reader = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8))
			{
				string value = reader.ReadToEnd();
				error?.Invoke(value);
			}
		}
		finally
		{
			if (reqstream != null)
			{
				reqstream.Close();
			}
			if (streamReceive != null)
			{
				streamReceive.Close();
			}
			if (response != null)
			{
				response.Close();
			}//很多时候释放了Stream和Response还不够,客户端的Request还是在保持着,需要等垃圾回收器来回收,所以一般很容易阻塞,导致请求发送不出去。加上这个就是让HttpWebRequest实例在不需要的时候及时释放资源。这样可以重复使用而不会阻塞。
			if (request != null)
			{
				request.Abort();
			}
		}
	}
}
—— 完 ——
相关推荐
评论

立 为 非 似

中 谁 昨 此

宵 风 夜 星

。 露 , 辰

文章点击榜

细 无 轻 自

如 边 似 在

愁 丝 梦 飞

。 雨 , 花