【C#】HttpWebRequest

HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。

HttpWebRequest对象不是利用new关键字通过构 造函数来创建的,而是利用工厂机制(factory mechanism)通过Create()方法来创建的。

提交数据方式:GET、POST

作用:对HTTP协议进行了完整的封装,对HTTP协议中的 Header, Content, Cookie 都做了属性和方法的支持,很容易就能编写出一个模拟浏览器自动登录的程序

    public class HttpAPI
    {
        public string selectAPI(string jsonStr)
        {
            string url = "http://10.72.3.0:8086/CSB";
            string result = "";//返回结果
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebResponse response;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址

                request.Accept = "text/html,application/xhtml+xml,*/*";
                request.ContentType = "application/json";
                //请求方式
                request.Method = "POST";
                //头文件
                request.Headers.Add("_api_timestamp", "1623325847266");
                request.Headers.Add("_api_name", "hssServives");
                request.Headers.Add("_api_version", "1.0.0");
                request.Headers.Add("_api_access_key", "3b78a66b1bb04183a0215b7b8e6e18e9");
                request.Headers.Add("_api_signature", "AYbcuYagEwhnbf+zr4CjVhqSRPs=");

                try
                {                                        
                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(jsonStr);//将URL编码后的字符串转化为字节             
                    request.ContentLength = payload.Length;//设置请求的 ContentLength 
                    System.IO.Stream stream = request.GetRequestStream();//获得请求流
                    stream.Write(payload, 0, payload.Length);//将请求参数写入流
                    stream.Close(); // 关闭请求流
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    response = (HttpWebResponse)ex.Response;
                }
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {                    
                    result = reader.ReadToEnd();
                    reader.Close();
                }
                if (response.StatusCode != HttpStatusCode.OK)//未成功格式化数据,返回响应码
                {
                    result = "Exception:" + result;
                }
                return result;
            }
            catch (WebException ex)
            {
                return "Exception:" + ex.Message;
            }
        }
    }

你可能感兴趣的:(C#,c#,http)