zoukankan      html  css  js  c++  java
  • C# HttpWebRequest请求服务器(Get/Post兼容)

    简单示例说明

    public static string HttpGet(string url, string data,string Method, int timeOut, Encoding encode, string contentType = "application/x-www-form-urlencoded", CookieContainer cookieContainer = null, string UserAgent = null)
    {
    string result = "";
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    try
    {
    webRequest.Method = Method;//请求方式Get/Post
    webRequest.Timeout = timeOut;//超时时间(毫秒单位)
    webRequest.ContentType = contentType;//请求参数格式
    webRequest.Accept = "*/*";//http标头多个以;隔开例:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    webRequest.UserAgent = UserAgent;//可为空
    webRequest.Headers.Add("Name", "admin");//添加http标头可多个
    webRequest.Headers.Add("Type", "1");//添加http标头可多个
    if (!string.IsNullOrEmpty(data))
    {
    byte[] buffer = encode.GetBytes(data); // 转化 encode编码格式例:Encoding.UTF8
    webRequest.ContentLength = buffer.Length;
    //写入提交数据
    using (System.IO.Stream newStream = webRequest.GetRequestStream())
    {
    newStream.Write(buffer, 0, buffer.Length); //写入参数
    newStream.Flush();
    }
    }
    //提交请求
    using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webRequest.GetResponse())
    {
    if (cookieContainer != null)
    {
    response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
    }
    //判断是否返回的是压缩信息
    if (response.ContentEncoding.ToLower().Contains("gzip"))
    {
    using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
    {
    using (StreamReader sreader = new StreamReader(stream))
    {
    result = sreader.ReadToEnd();
    }
    }
    }
    else
    {
    using (Stream stream = response.GetResponseStream())
    {
    using (StreamReader reader = new StreamReader(stream, encode))
    {
    result = reader.ReadToEnd();
    }
    }
    }
    }
    }
    catch (WebException ex)
    {
    LogHelper.WriteErrorLog("时间:" + DateTime.Now + "--路径" + url + "--错误:" + ex);//错误写入日志
    var httpErrResponse = ((HttpWebResponse)ex.Response);
    using (var stream = httpErrResponse.GetResponseStream())
    {
    if (stream != null)
    {
    using (var reader = new StreamReader(stream))
    {
    result = reader.ReadToEnd();
    }
    }
    }
    }
    return result;
    }

  • 相关阅读:
    docker file和容器数据卷,发布镜像
    Docker的镜像原理和分层理解和打包镜像
    docker部署nginx,tomcat 练习
    Docker 命令和运行原理简单剖析
    Docker安装
    Java垃圾回收-栈和堆部分知识
    aio-pika的使用
    技术基础 | 在Apache Cassandra中改变VNodes数量的影响
    行业动态 | 通过使用Apache Cassandra实现实时供应链管理
    行业动态 | Apache Pulsar 对现代数据堆栈至关重要的四个原因
  • 原文地址:https://www.cnblogs.com/ZxtIsCnblogs/p/12143744.html
Copyright © 2011-2022 走看看