HttpClient Post 提交表单数据

Posted elef

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient Post 提交表单数据相关的知识,希望对你有一定的参考价值。

运行环境 .net 4.6.1

//为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
var sslHandler = new HttpClientHandler()
{
};
sslHandler.ClientCertificateOptions = ClientCertificateOption.Manual;

ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback(delegate
{
    return true;
});
HttpClient client = new HttpClient(sslHandler, true);
//请求Headers
client.DefaultRequestHeaders.Add("Authorization", "WSSE realm="SDP",profile="UsernameToken",type="Appkey"");

//请求Body
var body = new Dictionary <string,string> ()
    {
        {
            "from", "sender"
        },
        {
            "to", "receiver"
        }
    };
HttpContent content = new FormUrlEncodedContent(body);
var response = client.PostAsync(apiAddress, content).Result;
Console.WriteLine(response.StatusCode); //打印响应结果码
var res = response.Content.ReadAsStringAsync();
Console.WriteLine(res.Result); //打印响应信息

运行环境dotnet core 2.2

//为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
HttpClient client = new HttpClient();
ServicePointManager.ServerCertificateValidationCallback = delegate
{
    return true;
};
//请求Headers
client.DefaultRequestHeaders.Add("Authorization", "WSSE realm="SDP",profile="UsernameToken",type="Appkey"");
//请求Body
var body = new Dictionary < string,
    string > ()
    {
        {
            "from", sender
        },
        {
            "to", receiver
        }
    };
HttpContent content = new FormUrlEncodedContent(body);
var response = client.PostAsync(apiAddress, content).Result;
Console.WriteLine(response.StatusCode); //打印响应结果码
var res = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(res); //打印响应信息

以上是关于HttpClient Post 提交表单数据的主要内容,如果未能解决你的问题,请参考以下文章

Java模拟POST表单提交HttpClient操作

使用 HttpClient POST 通过上传提交表单

如何通过HttpClient去POST一个multipart/form-data数据

安卓小案例收集二

httpclient模拟post请求json封装表单数据

使用异步httpclient框架做get,post提交数据