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;
    }

  • 相关阅读:
    Linux 上的数据可视化工具
    LINUX 暂停、继续进程
    77个常用Linux命令和工具
    必学100个常用linux命令大全
    Canny边缘检測算法原理及其VC实现具体解释(一)
    ACM POJ 2192 Zipper
    【实战】静默安装-oracle 11.2.0.3 on centos 5.10
    C++ 观察者模式样例
    access数据库:怎么直接从access里把数据里同样的文字替换成空字符""
    垂死挣扎还是涅槃重生 -- Delphi XE5 公布会归来感想
  • 原文地址:https://www.cnblogs.com/ZxtIsCnblogs/p/12143744.html
Copyright © 2011-2022 走看看