本文主要是介绍如何用HttpClient请求带参数的服务,请求服务为某翻译API
直接上源码
1.添加using System.Net;的引用
using System.Net;
2.使用HttpClient发送请求
public static async void Fanyin_HttpClient(string fromString)
{
Console.WriteLine($"Fanyin_HttpClient post");
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
string randnum = Random.Shared.Next(100).ToString();
string sign = Encrypt.EncryptString(ApiConfig.ApiId + fromString + randnum + ApiConfig.ApiKey);
var response = await httpClient.PostAsync(ApiConfig.Url, new FormUrlEncodedContent(new Dictionary<string, string>() {
{ "q",fromString},
{ "from",Language.中文简体},
{ "to",Language.英语},
{ "appid",ApiConfig.ApiId},
{ "salt",randnum},
{ "sign",sign}
}));
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
3.输出