问题
What's wrong with this code snippet in 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());
}
}
}
}
When running this with a breakpoint at the line response.EnsureSuccessStatusCode()
, I always get 502 response. However, if running this in Postman or in curl, I got back a valid result.
Example in curl:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "addr=1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P" "https://api.omniexplorer.info/v1/transaction/address"
Many thanks for helping a newbie out!
回答1:
The request uses application/x-www-form-urlencoded
so instead of StringContent
use FormUrlEncodedContent
:
var content = new FormUrlEncodedContent(req);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(uriBuilder.Uri, content);
来源:https://stackoverflow.com/questions/59236222/net-core-https-requests-returns-502-bad-gateway-while-postman-returns-200-ok