【问题标题】:HttpClient Get request with Body have Error C#HttpClient Get请求与Body有错误C#
【发布时间】:2020-04-08 09:58:53
【问题描述】:

我进行了很多研究,很多人提到不可能通过身体获取请求。我设法使用邮递员从它那里得到了回应。现在我想写我的代码,但我不知道该怎么做。我需要得到响应,但要让这个 url 起作用,我需要包含正文。有谁知道如何使用 C# 代码包含正文?

这是我当前的代码,但有一个错误 -> System.PlatformNotSupportedException: 'WinHttpHandler is only supported on .NET Framework and .NET Core runtimes on Windows. It is not supported for Windows Store Applications (UWP) or Unix platforms.'

 var handler = new WinHttpHandler();
        var client = new HttpClient(handler);

        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("my url"),
            Content = new StringContent("my json body content", Encoding.UTF8, "application/json"),
        };

        var response = await client.SendAsync(request).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();
        var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        string text = responsebody.ToString();
        string[] str = text.Split(new[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);
        string result = str[10];
        labelTxt.Text = result;

【问题讨论】:

  • 只需将代码更改为 var client = new HttpClient(); - 如果您不自定义 WinHttpHandler,那么如果您使用 HttpClient 的默认构造函数,它将为您的平台选择适当的内部处理程序。
  • 您可能应该使用HttpClientHandler 而不是Windows 特定的WinHttpHandler。尽管您似乎没有对处理程序做任何事情,所以只需按照@MartinCostello 的建议使用new HttpClient()
  • 这通常是个坏主意。它“有效”,但违反 HTTP 规范对 GET 请求的正文赋予任何含义。 stackoverflow.com/questions/978061/http-get-with-request-body
  • @MartinCostello 嗨!在将我的代码更改为您提到的内容后,它起作用了。谢谢:)

标签: c# api httpclient


【解决方案1】:

您在代码中使用了特定于 Windows 的 WinHttpHandler 类型,您不需要这样做,因为您没有自定义它,这就是导致异常的原因。

如果您将代码更改为以下内容,它应该适用于 .NET Core 上的任何平台:

var client = new HttpClient(); // Changed to use the default HttpClient constructor

var request = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri("my url"),
    Content = new StringContent("my json body content", Encoding.UTF8, "application/json"),
};

var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responsebody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
string text = responsebody.ToString();
string[] str = text.Split(new[] { ',', ':' }, StringSplitOptions.RemoveEmptyEntries);
string result = str[10];
labelTxt.Text = result;

【讨论】:

  • 嗨,这段代码在检索数据时确实有效,但我还有另一个错误 --> Android.Util.AndroidRuntimeException: 'Only the original thread that created a view hierarchy can touch its views.' 。你知道如何解决这个问题吗?
  • 抱歉,恐怕我帮不上那个忙。我不熟悉 Android/Xamarin 开发。我的猜测是它类似于后台线程无法更新主 UI 线程的 WinForms 应用程序。在这些情况下,您必须将后台线程中的数据提供给主 UI 线程,然后它会更新 UI 元素本身。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多