I have checked out every one of these similar questions and although they are similar, no solutions have been found.
The Problem:
I have implemented a very simple post request from my Xamarin mobile application to a PHP server, using HttpClient()
. The PHP server simply prints out any post request it is given, for now.
When I use Postman
to send my web server post requests, the PHP works perfectly, however attempting to send post requests from my mobile application results in an error:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Date: Fri, 03 Aug 2018 08:52:36 GMT Transfer-Encoding: chunked Connection: keep-alive Set-Cookie: __cfduid=d54d4c18d07eeae5179fde8e4533dd6881533286355; expires=Sat, 03-Aug-19 08:52:35 GMT; path=/; domain=.braz.io; HttpOnly; Secure Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Server: cloudflare CF-RAY: 44478c8b9d0c1d68-MEL Content-Type: 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;
}
}
It seems like I am missing a nuance with the PostAsync();
function. Why can I successfully do Post requests from Postman
but fail when using PostAsync()
on my mobile application?
After some discussion on SO:
I added string body = await response.Content.ReadAsStringAsync();
to see if the web server was sending any useful information about the error, back to my mobile application. Unfortunately it just sent back a simple 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"