c# 使用HttpClient的post,get方法传输json
2021-03-03 12:27
标签:get use mysql ali convert console async follow core 微软文档地址https://docs.microsoft.com/zh-cn/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2,只有get。post 的方法找了白天才解决 在阿里云上的.Net Core on Linux c# 使用HttpClient的post,get方法传输json 标签:get use mysql ali convert console async follow core 原文地址:https://www.cnblogs.com/guohu/p/12982850.htmlusing 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();
}
自己封装的类,我几乎所有的个人项目都用这个
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;
///
文章标题:c# 使用HttpClient的post,get方法传输json
文章链接:http://soscw.com/index.php/essay/59512.html