C# WebApi WebRequest/HttpWebRequest

WebRequest如何发送http请求?

引用

using System.Net;
using System.IO;

Base on Webreqution 

        public static string WebRequestByPost(string url, string contentType, string content, string Status)
        {
            string result;
            try
            {
                //1.Create request
                Uri uri = new Uri(url);
                WebRequest webRequest = WebRequest.Create(uri);
                //2.Set request type such like "application/json; charset=UTF-8";"text/xml; charset=utf-8";
                webRequest.ContentType = contentType;                
                webRequest.Method = Status;//POST or Get
                //3.If you need to set parameters or not dont need this
                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    byte[] paramBytes = Encoding.UTF8.GetBytes(content.ToString());
                    requestStream.Write(paramBytes, 0, paramBytes.Length);
                }
                //4.Recived responce of request
                WebResponse webResponse = webRequest.GetResponse();
                using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    result = myStreamReader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                throw new Exception("发送请求失败!");
            }
            return result;
        }

总结:使用方便,简介,缺点是请求无法设置cookie。

C# WebApi WebRequest/HttpWebRequest

上一篇:html 5 读取本地文件API


下一篇:FastAPI 高级编程(一) 错误处理