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

我们可以看到, 尽管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

微软文档地址https://docs.microsoft.com/zh-cn/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2,只有get。post 的方法找了白天才解决

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);//把收到的字符串序列化
    }
}
C# 使用 HttpClient 进行http GET/POST请求

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

C#中通过HttpClient发送Post请求相关推荐

  1. Ionic+Angular+Express实现前后端交互使用HttpClient发送get请求数据并加载显示(附代码下载)

    场景 Ionic介绍以及搭建环境.新建和运行项目: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106308166 在上面搭建起 ...

  2. Httpclient发送json请求

    一.Httpclient发送json请求 public String RequestJsonPost(String url){     String strresponse = null;     t ...

  3. HttpClient发送Https请求报 : unable to find valid certification path to requested target

    一.场景   近期在对接第三方接口时,通过HttpClient发送Https请求报 : unable to find valid certification path to requested tar ...

  4. HttpClient发送Get请求(java)【从新浪云搬运】

    直接上代码吧 public static void sendHttpGet(final String url){//发送Get请求的方法,url中已经带了需要的参数. new Thread(new R ...

  5. 爬虫 spider05——使用httpclient发送get请求、post请求

    百度解释 HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的 ...

  6. promise的应用和在VUE中使用axios发送AJAX请求服务器

    promise 用promise对函数封装: 原来的代码: <!DOCTYPE html> <html> <head><title>vue demo&l ...

  7. java httpclient发送json 请求 ,go服务端接收

    /***java客户端发送http请求*/package com.xx.httptest;/*** Created by yq on 16/6/27.*/import java.io.IOExcept ...

  8. 使用httpclient发送get请求

    private CloseableHttpClient httpClient = null;@BeforeClasspublic void setUpBeforeClass() {// 通过这个方法创 ...

  9. Java使用HttpClient发送Https请求证书失效:PKIX path building failed:

    最近使用HttpClient对接第三方短信接口,在进行本地测试时报了一个证书失效的错误. 1. 封装的HttpClient的Post请求 public static Map<String, Ob ...

最新文章

  1. python中的module
  2. 「人工智能训练师」国家职业技能标准发布:共有五级,您是第几级?
  3. MATLAB使用Python数值和字符变量
  4. 同一个项目相互调接口_超详细——接口测试总结与分享(一)
  5. Heritrix 1.14.4的配置和初次使用
  6. 2019_7_31python
  7. Win7下硬盘安装Redhat双系统
  8. 算法竞赛中的随机数产生和断言
  9. 域名中主机名是第几个_CentOS7系统如何修改主机名
  10. ETH突破620美元关口 日内涨幅为5.36%
  11. Java并发编程之CAS和AQS
  12. 在某个文件夹中打开 cmd黑窗口
  13. 条码打印软件如何实现二维码内容换行显示 1
  14. c语言mergesort 参数,求教关于归并排序MergeSort()的问题
  15. mybatis 小于号转义
  16. Go:实现Abs绝对值函数 (附完整源码)
  17. 规律化的办公室装修也要独特
  18. 全网营销都有那些渠道
  19. 2进制 16进制 计算机术语,十六进制转二进制计算器
  20. 营销革命4.0 从传统到数字

热门文章

  1. 在python中查看关键字、需要执行_python关键字以及含义,用法
  2. FIR设置过采样率 matlab,Xilinx FIR IP的介绍与仿真
  3. oracle没有imp.exe,imp.exe 文件下载
  4. android 极光推送测试,Android 3分钟带你集成极光推送
  5. 明日之后服务器维修会补偿什么,明日之后:服务器修复后官方发来补偿,玩家居然怀疑奖励不真实?...
  6. oracle 磁盘不分区吗,LINUX停ORACLE软件、数据文件等所在的磁盘分区空间不足的解决思路...
  7. php毕设周记_毕设周记
  8. 关于鸿蒙系统报告,华为鸿蒙操作系统研究报告:全景解构(21页)
  9. chrom禁用浏览器回退按钮不管用_什么?作为程序员你都工作了还不会用Git
  10. python设置图片透明度_学习python第40天