C#使用HttpClient四种请求数据格式:json、表单数据、文件上传、xml。现在流行前后端分离,后端提供对应服务接口给前端或跨应用程序调用,如WebAPI等。在调用这些服务接口发送HTTP请求,而.NET为我们提供了HttpWebRequest、HttpClient几个类库来实现。
一、JSON数据格式
application/json
引用
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Fountain.WinConsole.HttpDemo
代码
static async Task Main(string[] args)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
User user = new User();
user.username = "ceshi";
user.password = "123456";
string jsonData = JsonConvert.SerializeObject(user);
StringContent content = new StringContent(jsonData, Encoding.UTF8);
// 设置HTTP 响应上的ContentType --application/json
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// 请求访问地址
string url = "https://192.168.20.20/api/user/login";
// 发出HTTP的Post请求
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 读取返回结果
string responseContent = await response.Content.ReadAsStringAsync();
// 将字符转对象
Result result = JsonConvert.DeserializeObject<Result>(responseContent);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine();
}
二、表单数据格式
application/x-www-form-urlencoded
引用
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
代码
static async Task Main(string[] args)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
Dictionary<string,string> user = new Dictionary<string, string>
{
{ "username", "ceshi" },
{ "password", "123456" }
};
FormUrlEncodedContent content = new FormUrlEncodedContent(user);
// 请求访问地址
string url = "https://192.168.20.20/api/user/login";
// 发出HTTP的Post请求
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 读取返回结果
string responseContent = await response.Content.ReadAsStringAsync();
// 将字符转对象
Result result = JsonConvert.DeserializeObject<Result>(responseContent);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine();
}
三、文件上传格式
multipart/form-data
引用
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
代码
static async Task Main(string[] args)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
multipartContent.Add(new StringContent("user"), "test");
multipartContent.Add(new ByteArrayContent(File.ReadAllBytes(string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "test.jpg"))), "image", "test.jpg");
// 请求访问地址
string url = "https://192.168.20.20/api/user/upload";
// 发出HTTP的Post请求
HttpResponseMessage response = await httpClient.PostAsync(url, multipartContent);
// 读取返回结果
string responseContent = await response.Content.ReadAsStringAsync();
// 将字符转对象
Result result = JsonConvert.DeserializeObject<Result>(responseContent);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine();
}
}
四、XML数据格式
text/xml
引用
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
代码
static async Task Main(string[] args)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
StringBuilder user = new StringBuilder();
user.AppendLine("<usrname>ceshi</usrname>");
user.AppendLine("<password>123456</password>");
string xmlData = user.ToString();
StringContent content = new StringContent(xmlData, Encoding.UTF8);
// 设置HTTP 响应上的ContentType --text/xml
content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
// 请求访问地址
string url = "https://192.168.20.20/api/user/login";
// 发出HTTP的Post请求
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 读取返回结果
string responseContent = await response.Content.ReadAsStringAsync();
// 将字符转对象
Result result = JsonConvert.DeserializeObject<Result>(responseContent);
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine();
}
HttpClient的一些属性与方法。
属性:
BaseAddress
获取或设置发送请求时地址。
DefaultProxy
获取或设置全局HTTP请求代理。
DefaultRequestHeaders
获取请求发送的标题。
DefaultRequestVersion
获取或设置请求使用的默认HTTP版本。
MaxResponseContentBufferSize
获取或设置读取响应内容时要缓冲的最大字节数。
Timeout
获取或设置请求超时等待的时间。
方法:
GetAsync
异步请求获取指定URI。
GetByteArrayAsync
异步请求获取指定URI并以字节数组的形式返回响应。
GetStreamAsync
异步请求获取指定URI并以流的形式返回响应。
GetStringAsync
异步请求获取指定URI并以字符串的形式返回响应正文。
PostAsync
异步将POST请求发送给指定URI。
Send
发送带有指定请求的 HTTP 请求。
SendAsync
以异步操作发送 HTTP 请求。
阅读原文:原文链接
该文章在 2025/2/17 12:23:54 编辑过