Xamarin Forms-simple PostAsync()返回错误400错误请求



我已经检查了这些类似的问题中的每一个,尽管它们很相似,但没有找到解决方案。

问题:

我使用HttpClient()实现了一个从Xamarin移动应用程序到PHP服务器的非常简单的post请求。目前,PHP服务器只是打印出它收到的任何post请求。

当我使用Postman发送我的web服务器发布请求时,PHP工作得很好,但试图从我的移动应用程序发送发布请求会导致一个错误:

{StatusCode:400,ReasonPhrase:"错误请求",版本:1.1,内容:System.Net.Http.StreamContent,标头:{日期:2018年8月3日星期五08:52:36 GMT传输编码:分块连接:保持活动设置Cookie:__cfduid=d54d4c18d07eeae5179fde8e4533dd6881533286355;expires=2019年8月3日星期六08:52:35 GMT;路径=/;domain=.brazz.io;HttpOnly;保护预计CT:最大年龄=604800,报告uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"服务器:cloudflareCF-RAY:444478c8b9d0c1d68 MEL内容类型:text.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();函数的一个细微之处。为什么在移动应用程序上使用PostAsync()时,我可以成功执行来自Postman的Post请求,但失败了?

经过对SO的讨论:

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

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

这是我偶然发现的解决方案(如果有人能在评论中写下/编辑这个答案,说明为什么这是一个很棒的解决方案!(

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

最新更新