张德长

导航

C# 发起网络请求

 public class CWebRequest
    {
        //从URL读取内容
        //流程:创建网络请求对象→获取响应→获取响应流→从响应留读取字符串
        //流程:WebRequest→WebResponse→Stream→StreamReader→ReadToEnd
        public string GetResponseContent(string url)
        {
            WebRequest request = WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string res = reader.ReadToEnd();
            reader.Dispose();
            stream.Dispose();
            return res;
        }

        public string GetHttpResponseContent(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Dispose();
            stream.Dispose();
            return content;

        }
        //发起POST请求,并获取返回字符串
        //流程:创建请求→配置请求→获取请求流→Json写入请求流→获取响应→获取响应流→构建流读取器→读取相应字符串
        //流程:HttpWebRequest→(Method/ContentType)→GetRequestStream→Write→GetResponse→GetResponseStream→StreamReader→ReadToEnd
        //json转字节数组并获取长度
        public string PostJson(string url, string json)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            int len = bytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, len);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8);
            string responseContent = responseReader.ReadToEnd();
            responseReader.Dispose();
            responseStream.Dispose();
            requestStream.Dispose();
            return responseContent;
        }
    }

posted on 2023-04-14 12:07  张德长  阅读(71)  评论(0编辑  收藏  举报