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)
{
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());
}
}
}
}
在行response.EnsureSuccessStatusCode()
上使用断点运行此命令时,我总是得到502响应。但是,如果在Postman或curl中运行它,我会得到一个有效的结果。
卷曲示例:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "addr=1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P" "https://api.omniexplorer.info/v1/transaction/address"
非常感谢您帮助新手!
答案 0 :(得分:1)
该请求使用application/x-www-form-urlencoded
,因此使用StringContent
代替FormUrlEncodedContent
:
var content = new FormUrlEncodedContent(req);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(uriBuilder.Uri, content);