在客户机向服务器请求数据的时候,最常用的是GET和POST方法。

两者的主要区别是,GET把参数放到URL里发送请求,POST把参数放到包体里发送请求,相较于GET,POST请求更加安全。

一般POST请求的包体里放的是JSON格式的数据。

这里将C#程序里用的GET方法和POST方法封装成一个类,方便调用。

类里的HttpGet方法是用来发送GET请求的,包含重载方法,一个是包含请求头的,一个是不包含请求头的。

HttpPost方法用来发送Post请求,可以将json的字符串数据发送到指定地址中。

class HttpRequest
{
    /// <summary>
    /// GET方式请求数据
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <returns></returns>
    public static string HttpGet(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Accept = "*/*";
        request.Timeout = 15000;
        request.AllowAutoRedirect = false;

        WebResponse response = null;
        string responseStr = null;

        try
        {
            response = request.GetResponse();

            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            request = null;
            response = null;
        }

        return responseStr;
    }

    /// <summary>
    /// GET方式请求数据
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="header">请求头名称</param>
    /// <param name="headerValue">请求头值</param>
    /// <returns></returns>
    public static string HttpGet(string url, string header, string headerValue)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.Accept = "*/*";
        request.Timeout = 10000;
        request.AllowAutoRedirect = false;

        //添加报头
        request.Headers.Add(header, headerValue);

        WebResponse response = null;
        string responseStr = null;

        try
        {
            response = request.GetResponse();

            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseStr = reader.ReadToEnd();
                reader.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            request = null;
            response = null;
        }

        return responseStr;
    }


    /// <summary>
    /// POST方式请求数据
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="content">POST提交数据内容(utf-8编码的json)</param>
    /// <returns></returns>
    public static string HttpPost(string url, string content)
    {
        Encoding e = null;
        Regex s_charsetRegex = new Regex("charset=([^;]*);?");
        HttpWebRequest req = WebRequest.CreateHttp(url);
        var buffer = Encoding.UTF8.GetBytes(content);
        req.Method = "POST";
        req.ContentType = "application/json";
        req.ContentLength = buffer.Length;
        using (var fs = req.GetRequestStream())
        {
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
        }
        WebResponse resp = null;
        try
        {
            resp = req.GetResponse();
        }
        catch (WebException ex)
        {
            resp = ex.Response;
            if (resp != null)
            {
                resp.Close();
            }
            throw;
        }

        var ns = resp.GetResponseStream();
        Stream stream = ns;
        if (e == null)
        {
            if (resp.SupportsHeaders)
            {
                var m = s_charsetRegex.Match(resp.ContentType);
                if (m.Success)
                {
                    e = Encoding.GetEncoding(m.Groups[1].Value);
                }
                var contentEncoding = resp.Headers.Get("Content-Encoding");
                if (contentEncoding == "gzip")
                {
                    stream = new GZipStream(ns, CompressionMode.Decompress);
                }
                else if (contentEncoding == "deflate")
                {
                    stream = new DeflateStream(ns, CompressionMode.Decompress);
                }
            }
            if (e == null)
            {
                e = Encoding.UTF8;
            }
        }
        var reader = new StreamReader(stream, e);
        return reader.ReadToEnd();
    }
}

如果出现”WebRequest”未包含”CreateHttp”的定义这一类的问题,说明项目的目标框架版本太低,需要修改成.net framework 4.5或更高版本。

报错提示文本
遇到图中报错时需升级目标框架版本

更改目标框架

 
返回顶部