.net core HTTPS requests returns 502 bad gateway while Postman returns 200 OK

自作多情 提交于 2021-02-08 09:31:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!