欢迎加入Unity业内qq交流群:956187480
qq扫描二维码加群
public class HttpWebRequestTest : MonoBehaviour
{string url = "http://........";string token = "asd1212adsa1d651dwfedf1sdf";//发送以post方式发送http请求,并将参数以json格式传递到body体中public string HttpPost(){HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "POST";request.ContentType = "application/json";request.Headers.Add("token", token);//序列化为字符串,可以使用自己项目中封装的json方法string strContent = "{\"userName\": \"admin\",\"password\": \"123456\"}";using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream())){dataStream.Write(strContent);dataStream.Close();}HttpWebResponse response = (HttpWebResponse)request.GetResponse();string encoding = response.ContentEncoding;if (encoding == null || encoding.Length < 1){encoding = "UTF-8"; //默认编码 }StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));string retString = reader.ReadToEnd();return retString;}public string HttpGet(){string result = "";HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);req.Method = "GET";req.Headers.Add("token", token);HttpWebResponse resp = (HttpWebResponse)req.GetResponse();string encoding = resp.ContentEncoding;if (encoding == null || encoding.Length < 1){encoding = "UTF-8"; //默认编码 }//获取内容using (StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(encoding))){result = reader.ReadToEnd();reader.Close();}return result;}
}
欢迎加入Unity业内qq交流群:956187480
qq扫描二维码加群