C#中通过HttpClient发送Post请求

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

C#中HttpClient进行各种类型的传输

C#中通过HttpClient发送Post请求

我们可以看到, 尽管PostAsync有四个重载函数, 但是接受的都是HttpContent, 而查看源码可以看到, HttpContent是一个抽象类

那我们就不可能直接创建HttpContent的实例, 而需要去找他的实现类, 经过一番研究, 发现了, 如下四个:

MultipartFormDataContent、FormUrlEncodedContent、StringContent、StreamContent

和上面的总结进行一个对比就能发现端倪:

MultipartFormDataContent=》multipart/form-data

FormUrlEncodedContent=》application/x-www-form-urlencoded

StringContent=》application/json等

StreamContent=》binary

而和上面总结的一样FormUrlEncodedContent只是一个特殊的StringContent罢了, 唯一不同的就是在mediaType之前自己手动进行一下URL编码罢了(这一条纯属猜测, 逻辑上应该是没有问题的).

c# 使用HttpClient的post,get方法传输json

————————————————

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Timers;
using Newtonsoft.Json;
using System.Net.Http;
using System.IO;
using System.Net;
public class user
        {
            public string password;//密码hash
            public string account;//账户
        }

        static async void TaskAsync()
        {

            
            using (var client = new HttpClient())
            {
                
                try
                {
                    //序列化
                    user user = new user();
                    user.account = "zanllp";
                    user.password = "zanllp_pw";
                    var str = JsonConvert.SerializeObject(user);

                    HttpContent content =new StringContent(str);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    HttpResponseMessage response = await client.PostAsync("http://255.255.255.254:5000/api/auth", content);//改成自己的
                    response.EnsureSuccessStatusCode();//用来抛异常的
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync("http://255.255.255.254:5000/api/auth");
                    response.EnsureSuccessStatusCode();//用来抛异常的
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }
        }
 static void Main(string[] args)
        {
            TaskAsync();
            
            Console.ReadKey();
        }
 
在阿里云上的.Net Core on Linux

自己封装的类,我几乎所有的个人项目都用这个
using ICSharpCode.SharpZipLib.GZip;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

/// <summary>
/// 基于HttpClient封装的请求类
/// </summary>
public class HttpRequest
{
    /// <summary>
    /// 使用post方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <param name="json">发送的参数字符串,只能用json</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> PostAsyncJson(string url, string json)
    {
        HttpClient client = new HttpClient();
        HttpContent content = new StringContent(json);
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        return responseBody;
    }

    /// <summary>
    /// 使用post方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <param name="data">发送的参数字符串</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> PostAsync(string url, string data, Dictionary<string, string> header = null, bool Gzip = false)
    {
        HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
        HttpContent content = new StringContent(data);
        if (header != null)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }
        }
        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string responseBody = "";
        if (Gzip)
        {
            GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
            responseBody = new StreamReader(inputStream).ReadToEnd();
        }
        else
        {
            responseBody = await response.Content.ReadAsStringAsync();

        }
        return responseBody;
    }

    /// <summary>
    /// 使用get方法异步请求
    /// </summary>
    /// <param name="url">目标链接</param>
    /// <returns>返回的字符串</returns>
    public static async Task<string> GetAsync(string url, Dictionary<string, string> header = null, bool Gzip = false)
    {

        HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false });
        if (header != null)
        {
            client.DefaultRequestHeaders.Clear();
            foreach (var item in header)
            {
                client.DefaultRequestHeaders.Add(item.Key, item.Value);
            }
        }
        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();//用来抛异常的
        string responseBody = "";
        if (Gzip)
        {
            GZipInputStream inputStream = new GZipInputStream(await response.Content.ReadAsStreamAsync());
            responseBody = new StreamReader(inputStream).ReadToEnd();
        }
        else
        {
            responseBody = await response.Content.ReadAsStringAsync();

        }
        return responseBody;
    }

    /// <summary>
    /// 使用post返回异步请求直接返回对象
    /// </summary>
    /// <typeparam name="T">返回对象类型</typeparam>
    /// <typeparam name="T2">请求对象类型</typeparam>
    /// <param name="url">请求链接</param>
    /// <param name="obj">请求对象数据</param>
    /// <returns>请求返回的目标对象</returns>
    public static async Task<T> PostObjectAsync<T, T2>(string url, T2 obj)
    {
        String json = JsonConvert.SerializeObject(obj);
        string responseBody = await PostAsyncJson(url, json); //请求当前账户的信息
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
    }

    /// <summary>
    /// 使用Get返回异步请求直接返回对象
    /// </summary>
    /// <typeparam name="T">请求对象类型</typeparam>
    /// <param name="url">请求链接</param>
    /// <returns>返回请求的对象</returns>
    public static async Task<T> GetObjectAsync<T>(string url)
    {
        string responseBody = await GetAsync(url); //请求当前账户的信息
        return JsonConvert.DeserializeObject<T>(responseBody);//把收到的字符串序列化
    }
}
————————————————
版权声明:本文为CSDN博主「luckyone906」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011555996/article/details/116721769

C# 使用 HttpClient 进行http GET/POST请求文章来源地址https://www.toymoban.com/news/detail-433250.html

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace HTTPRequest
{
    class Program
    {
        static void Main(string[] args)
        {
           
            HttpClient httpClient = new HttpClient();
            Task<byte[]> task0= httpClient.GetByteArrayAsync("http://127.0.0.1");
            task0.Wait();
           // while (!task0.IsCompletedSuccessfully) { };
            byte[] bresult=task0.Result;
            string sresult = System.Text.Encoding.Default.GetString(bresult);
            Console.WriteLine(sresult);
          //  Console.ReadLine();
            -------
            HttpClient httpClient0 = new HttpClient();
            List<KeyValuePair<string, string>> param = new List<KeyValuePair<string, string>>();
            param.Add(new KeyValuePair<string, string>("xx", "xx"));
           Task<HttpResponseMessage> responseMessage  =httpClient0.PostAsync("http://localhost:1083/Home/Test", new FormUrlEncodedContent(param));
            responseMessage.Wait();
           Task<string> reString= responseMessage.Result.Content.ReadAsStringAsync();
            reString.Wait();
            Console.WriteLine(reString.Result);
            Console.ReadLine();
 
        }
    }
}
————————————————
版权声明:本文为CSDN博主「luckyone906」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011555996/article/details/116721769

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

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

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

相关文章

  • 使用C#发送HTTP的Get和Post请求

    2024年02月07日
    浏览(41)
  • vue使用axios发送post请求携带json body参数,后端使用@RequestBody进行接收

    最近在做自己项目中,做一个非常简单的新增用户场景,但是使用原生axios发送post请求的时候,还是踩了不少坑的。 唉,说多了都是泪,小小一个新增业务,在自己前后端一起开发的时候,硬是搞了好久。 下面就把问题总结分享下,防止后人再踩坑。 首先先看下我的接口定

    2024年02月02日
    浏览(40)
  • C语言通过IXMLHTTPRequest以get或post方式发送http请求获取服务器文本或xml数据

    做过网页设计的人应该都知道ajax。 Ajax即Asynchronous Javascript And XML(异步的JavaScript和XML)。使用Ajax的最大优点,就是能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变的信息。 在IE浏览器中,Ajax技术就是

    2024年01月25日
    浏览(41)
  • C# 通过 HttpWebRequest发送数据以及服务器通过Request请求获取数据

    C#中HttpWebRequest的用法详解 可参考: C#中HttpWebRequest的用法详解 C# HttpWebRequest详解 C# 服务器通过Request获取参数 可参考: C# WebService 接口 通过Request请求获取json参数 1、后台程序发送HTTP请求的Class,服务器端也要添加该类 2、服务端返回HTTP请求的数据class,客户端也要有 1、后台

    2024年02月06日
    浏览(43)
  • HTTP POST接口带参数的HttpClient请求方法和调用

    接口自动化测试,今天遇到POST接口带参数,参数在url上,发现原来的工具类中没有该方法,重新调试加上。  doPost方法如下: 参考: [Java 接口自动化框架]httpclient4.5.3(CloseableHttpClient) https的工具类HttpsClientUtils

    2024年02月06日
    浏览(36)
  • Java HttpClient 实战 GET 与 POST 请求一网打尽

    在Java中, HttpClient 是进行HTTP通信的一个强大工具。它提供了简单而灵活的API,可以轻松地发送HTTP请求并处理响应。在本篇博文中,我们将深入探讨如何使用 HttpClient 执行GET、POST等不同类型的HTTP请求。 首先,确保在项目的 pom.xml 文件中引入 HttpClient 的依赖: 让我们从一个简

    2024年01月17日
    浏览(35)
  • libcurl是一个用于进行网络通信的开源库,提供了各种功能和选项,可以用于发送和接收HTTP请求、FTP操作等

    libcurl是一个用于进行网络通信的开源库,提供了各种功能和选项,可以用于发送和接收HTTP请求、FTP操作、SMTP邮件等。它支持多种协议,包括HTTP、HTTPS、FTP、FTPS、SMTP、POP3、IMAP等。 以下是libcurl库的一些特点和功能: 跨平台:libcurl可在多个操作系统上使用,包括Windows、Lin

    2024年01月19日
    浏览(35)
  • Java发起Post 、Get 各种请求整合

    java发起get请求和post请求的各种情况整合。具体看代码以及注释。其中Constants.UTF8本质是指\\\"UTF-8\\\"

    2024年02月04日
    浏览(40)
  • 云函数发送post请求

    1、新建云函数 2、在云函数目录,右键-外部终端 3、npm install got@10 注意要控制版本 4、云函数上传后,在云开发配置-高级配置,修改超时时间到更长 5、请求内容 const cloud = require(\\\'wx-server-sdk\\\') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境 const got = require(\\\'got\\\') // 云函数

    2023年04月11日
    浏览(29)
  • 在postman中使用raw纯文本格式发送POST请求成功而在python爬虫中发送POST请求失败

    在postman中是成功的 我查了很多资料,说raw是纯文本格式提交的,我又去看postman中的headers,查看content-Type中指定了格式 修改了爬虫中的headers 或者把data写出字典格式,再用json.dumps(data)转换一下

    2024年02月12日
    浏览(46)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包