C# .net核心HTTPS请求返回502个坏网关,而Postman返回200个OK
C#.NET core 3中的此代码段有什么问题:C# .net核心HTTPS请求返回502个坏网关,而Postman返回200个OK,c#,post,https,.net-core,dotnet-httpclient,C#,Post,Https,.net Core,Dotnet Httpclient,C#.NET core 3中的此代码段有什么问题: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static async Task Main(string[] args)
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
var uriBuilder = new UriBuilder
{
Scheme = Uri.UriSchemeHttps,
Host = "api.omniexplorer.info",
Path = "v1/transaction/address",
};
var req = new Dictionary<string, string>
{
{ "addr", "1FoWyxwPXuj4C6abqwhjDWdz6D4PZgYRjA" }
};
using(var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(uriBuilder.Uri, new StringContent(JsonConvert.SerializeObject(req)));
response.EnsureSuccessStatusCode();
Console.WriteLine(response.Content.ToString());
}
}
}
}
非常感谢你帮助一个新手 请求使用
application/x-www-form-urlencoded
,因此使用FormUrlEncodedContent
代替StringContent
:
var content = new FormUrlEncodedContent(req);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(uriBuilder.Uri, content);
哇,谢谢你。这很有效。但是,我必须删除行
content.Headers.Add(“content-Type”,“application/x-www-form-urlencoded”)代码>因为它会产生一个异常:无法添加值,因为标题“Content Type”不支持多个值。
我们应该调用类似于Content.Headers.Clear()的东西吗
first?@user\u 0\u发现我已经更新了答案-有一个ContentType
属性FormUrlEncodedContent
,应该使用它而不是标题。添加。希望现在对你有用
var content = new FormUrlEncodedContent(req);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(uriBuilder.Uri, content);