C#——HTTP请求

这篇具有很好参考价值的文章主要介绍了C#——HTTP请求。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、Get请求

使用HttpWebRequest进行Get请求:

public static string get(string url)
{
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
    string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
    reader.Close();
    myResponse.Close();
    return returnXml;
}

使用HttpClient进行异步Get请求:

public static string GetData(string url,string data)
{
    string strResult = "";
    try
    {
        url = url+ "?" + data;

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.GetAsync(url).Result;

        if (response.IsSuccessStatusCode)
        {
            strResult = response.Content.ReadAsStringAsync().Result;
        }
    }
    catch (Exception)
    {

        throw;
    }

    return strResult;
}

2、Post请求

使用HttpClient 进行异步的Post请求:

/// <summary>
/// 接口调用
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string PostData(string url, string data)
{
    string strResult = "";
    try
    {
        var str = JsonConvert.SerializeObject(data);
        var httpContent = new StringContent(str, Encoding.UTF8, "application/json");

        //string url = GetConfigUrl(encode);

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

        if (response.IsSuccessStatusCode)
        {
            strResult = response.Content.ReadAsStringAsync().Result;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return strResult;
}

 使用System.Net.HttpWebRequest的Post请求:

public static string sendPost(string url, string postData)
{
    System.Net.HttpWebRequest webrequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
    webrequest.Method = "post";
    webrequest.ContentType = "application/json";
    byte[] postdatabyte = Encoding.UTF8.GetBytes(postData);
    webrequest.ContentLength = postdatabyte.Length;
    Stream stream;
    stream = webrequest.GetRequestStream();
    stream.Write(postdatabyte, 0, postdatabyte.Length);
    stream.Close();
    using (var httpWebResponse = webrequest.GetResponse())
    using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        String ret = responseStream.ReadToEnd();
        string result = ret.ToString();
        return result;
    }
}

3、使用HttpWebRequest的Cookie的跨登录请求

登录获取Cookie:

CookieContainer globeCookie = new CookieContainer();

public static string DoPostLogin(string url, string data, ref CookieContainer myCookieContainer)
{
    try
    {
        HttpWebRequest webRequest = GetWebRequest(url, "POST");
        webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        webRequest.CookieContainer = myCookieContainer;
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        Stream requestStream = webRequest.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();
        HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
        myCookieContainer.Add(httpWebResponse.Cookies);
        Encoding encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
        return GetResponseAsString(httpWebResponse, encoding);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

使用登录取到的Cookie去访问接口:

public static string DoPost(string url, string data, CookieContainer inputCookieContainer)
{
    try
    {
        HttpWebRequest webRequest = GetWebRequest(url, "POST");
        webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
        webRequest.CookieContainer = inputCookieContainer;
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        Stream requestStream = webRequest.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();
        HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
        Encoding encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
        return GetResponseAsString(httpWebResponse, encoding);
    }
    catch (Exception ex)
    {
        return ex.Message;
    }
}

读取HttpWebResponse

public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
    Stream responseStream = null;
    StreamReader reader = null;
    string str;
    try
    {
        responseStream = rsp.GetResponseStream();
        reader = new StreamReader(responseStream, encoding);
        str = reader.ReadToEnd();
    }
    finally
    {
        if (reader != null)
        {
            reader.Close();
        }
        if (responseStream != null)
        {
            responseStream.Close();
        }
        if (rsp != null)
        {
            rsp.Close();
        }
    }
    return str;
}

4、请求form表单

public static string PostDS(string url, string data, string ticket)
        {
            string result = "";
            try
            {
                string SendMessageAddress = url;//请求链接
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SendMessageAddress);
                request.Method = "POST";
                request.AllowAutoRedirect = true;
                //request.Timeout = 20 * 1000;
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Authorization", ticket);
                //string PostData = "a=1&b=2";//请求参数格式
                string PostData = data;//请求参数
                byte[] byteArray = Encoding.Default.GetBytes(PostData);
                request.ContentLength = byteArray.Length;
                using (Stream newStream = request.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    newStream.Close();
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream rspStream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    rspStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
                result = "false";
            }
            return result;
        }

5、创建https的HttpWebRequest请求文章来源地址https://www.toymoban.com/news/detail-505078.html

public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
    return true;
}

public static HttpWebRequest GetWebRequest(string url, string method)
{
    HttpWebRequest request;
    if (url.Contains("https"))
    {
        //用于验证服务器证书的回调
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
    }
    else
    {
        request = (HttpWebRequest)WebRequest.Create(url);
    }
    request.Method = method;
    request.Timeout = 0x186a0;
    return request;
}

到了这里,关于C#——HTTP请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Python中使用HTTP代理进行网络请求

    在Python中,HTTP代理是一种常用的技术,用于控制和修改HTTP请求和响应。通过使用HTTP代理,我们可以更好地控制网络请求的行为,提高安全性、隐私性和效率。下面我们将详细介绍如何在Python中使用HTTP代理进行网络请求。 一、HTTP代理的原理 HTTP代理是一种服务器,它位于客

    2024年01月19日
    浏览(55)
  • Python使用HTTP代理进行API请求的优化

    在Python中,HTTP代理是一种常用的技术,用于控制和修改HTTP请求和响应。通过使用HTTP代理,我们可以更好地控制网络请求的行为,提高安全性、隐私性和效率。下面我们将详细介绍如何在Python中使用HTTP代理进行API请求的优化。 一、减少请求次数 使用HTTP代理可以帮助我们减少

    2024年01月22日
    浏览(43)
  • 游戏服务器中使用Netty进行Http请求管理

    作为游戏服务器,无法避免与第三方系统交互。例如:登陆、充值、中台等,这些平台很多都是Web平台,提供http服务接口。这就需要游戏具备http访问功能。 Netty实现异步http调用。 效率:netty的多路复用技术,实现的异步http可以用很少的几个线程实现同时成百上千个http请求

    2024年02月08日
    浏览(34)
  • 【SpringBoot】springboot使用RestTemplate 进行http请求失败自动重试

    我们的服务需要调用别人的接口,由于对方的接口服务不是很稳定,经常超时,于是需要增加一套重试逻辑。这里使用 Spring Retry 的方式来实现。 一、引入POM 二、 修改启动类 在Spring Boot 应用入口启动类,也就是配置类的上面加上 @EnableRetry 注解,表示让重试机制生效。 注意

    2024年02月08日
    浏览(34)
  • .NET Core(C#)使用Titanium.Web.Proxy实现Http(s)代理服务器监控HTTP请求

    关于Titanium.Web.Proxy详细信息可以去这里仔细看看,这里只记录简单用法 NuGet直接获取Titanium.Web.Proxy 配置 与其说是配置,不如就说这一部分就是未来你需要使用的部分,想知道具体每个部分是干什么的就去看原文链接 全放过来太占地方 最后的 Console.Read(); 是一个等待函数,你

    2024年02月09日
    浏览(45)
  • C# HttpWebRequest详解

    HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择。它们支持一系列有用的属性。这两个类位 于System.Net命名空间,默认情况下这个类对于控制台程序来说是可访问的。请注意,HttpWebRequest对象不是利用new通过构 造函数来创建的,而是利用工厂机制(fact

    2024年02月01日
    浏览(16)
  • C#中HttpWebRequest的用法

    HttpWebRequest是一个常用的类,用于发送和接收HTTP请求。在C#中使用HttpWebRequest可以实现各种功能,包括发送GET和POST请求、处理Cookie、设置请求头、添加参数等。本文将深入介绍HttpWebRequest的用法,并给出一些常见的示例。 使用HttpWebRequest发送GET请求非常简单,只需指定目标UR

    2024年03月22日
    浏览(27)
  • 轻松理解Java中的public、private、static和final

    一、概念 1、public和private 两个都是访问权限修饰符,用于控制外界对类内部成员的访问。 public:表明对象成员是完全共有的,外界可以随意访问。用public修饰的数据成员、成员函数是对所有用户开放的,所有用户都可以直接进行调用。 private:表明对象成员是完全私有的,不

    2024年02月16日
    浏览(33)
  • 从public static void main(String[] args)看如何构造数据

    java语言中public static void main(String[] args)里面的ages有什么作用? 在Java语言中, public static void main(String[] args) 是一个特殊的方法,它是Java程序的入口点。当你运行一个Java程序时,程序会从这个方法开始执行。这个方法的参数 String[] args 是一个字符串数组,用于传递命令行参数

    2024年02月12日
    浏览(84)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包