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); //打印响应信息

posted @ 2020-01-21 15:17  elef  阅读(1498)  评论(0编辑  收藏  举报