【问题标题】:Xamarin Forms - simple PostAsync() returns error 400 bad requestXamarin Forms - 简单的 PostAsync() 返回错误 400 错误请求
【发布时间】:2018-08-03 19:40:44
【问题描述】:

我已经检查了these 的每一个类似问题,虽然它们相似,但没有找到解决方案。

问题:

我使用HttpClient() 实现了从我的 Xamarin 移动应用程序到 PHP 服务器的非常简单的发布请求。 PHP 服务器现在只是简单地打印出它给出的任何 post 请求。

当我使用Postman 发送我的网络服务器发布请求时,PHP 运行良好,但是尝试从我的移动应用程序发送发布请求会导致错误:

{StatusCode:400,ReasonPhrase:“错误请求”,版本:1.1,内容:System.Net.Http.StreamContent,标头: { 日期:格林威治标准时间 2018 年 8 月 3 日星期五 08:52:36 传输编码:分块 连接:保持活动 设置 Cookie:__cfduid=d54d4c18d07eeae5179fde8e4533dd6881533286355; expires=星期六,19 年 8 月 3 日 08:52:35 GMT;路径=/;域=.braz.io;仅http;安全的 Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" 服务器:cloudflare CF-RAY:44478c8b9d0c1d68-MEL 内容类型:文本/html }}

public class RestService
{
    HttpClient client;
    private const string URL = "https://braz.io/mobile.php";

    public RestService()
    {
        client = new HttpClient();
        client.MaxResponseContentBufferSize = 256000;
    }

    public async Task<string> getUserInformation(string username, string password)
    {
        var uri = new Uri(string.Format(URL, string.Empty));
        try
        {
            StringContent s = new StringContent("HELLO WORLD");
            var response = await client.PostAsync(uri, s);
        }
        catch (Exception ex)
        {Console.WriteLine(ex);}
        return null;
    }
}

似乎我缺少PostAsync(); 函数的细微差别。为什么我可以成功地从Postman 发出 Post 请求,但在我的移动应用程序上使用 PostAsync() 时却失败了?

经过一些关于 SO 的讨论:

我添加了string body = await response.Content.ReadAsStringAsync(); 以查看 Web 服务器是否正在将有关错误的任何有用信息发送回我的移动应用程序。不幸的是,它只是发回了一个简单的ERROR 400 webpage

   <html>\r\n<head><title>400 Bad Request</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>400 Bad Request</h1></center>\r\n<hr><center>openresty/1.11.2.4</center>\r\n</body>\r\n</html>\r\n"

【问题讨论】:

  • 可能有很多原因。我建议首先检查响应的正文,看看它是否提供了有关请求错误原因的详细信息。
  • 我将使用完整的错误消息编辑我的问题
  • 不,您需要阅读回复string body = await response.Content.ReadAsStringAsync(); 的正文,看看它是否有任何重要细节。有时服务器会在响应中提供详细信息。
  • 看来你描述的上面的函数只是给我返回了一个简单的400 Bad Requesthtml页面,我将它添加到问题中
  • 因为您没有发送正确的内容类型?

标签: rest asynchronous xamarin post


【解决方案1】:

这是我偶然发现的解决方案(如果有人可以在 cmets 中写/编辑这个答案,为什么这是一个很棒的解决方案!)

右键单击Android项目-> Android选项->高级->将HttpClient implementationDefault更改为Android

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-28
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2015-04-06
    • 1970-01-01
    相关资源
    最近更新 更多