简体   繁体   中英

How to make HTTP POST web request on xamarin?

I am trying to do a post to work. It works on Postman but it doesn't work on my app. It seems to hit the timeout.

jbx.sellos.com.br/v1/auth

I am using this code:

public async void GetToken(string strUserName, string strPassword)
{
    var client = new HttpClient();
    object userInfo = new { username = "root", password = "toor" };

    var jsonObj = JsonConvert.SerializeObject(userInfo);

    var content = new StringContent(jsonObj, Encoding.UTF8, "application/json");

    HttpResponseMessage response = client.PostAsync(RequestUri(), content).Result;

    var result = await response.Content.ReadAsStringAsync();
}

Here is also another code I have tried:

public async Task<bool> Test()
{
    HttpClient client = new HttpClient();

    object userInfo = new { username = "root", password = "toor" };

    var jsonObj = JsonConvert.SerializeObject(userInfo);

    var content = new StringContent(jsonObj, Encoding.UTF8, "application/json");

    try
    {
        HttpResponseMessage response = await client.PostAsync(RequestUri(), content);

        var result = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
        {
            return true;
        }

        return false;
    }
    catch (Exception e)
    {
        return false;
    }
}

In all situations, the code runs till HttpResponseMessage response = await client.PostAsync(RequestUri(), content); after this, the app keep running but after a few moments I get a message "The application is in break mode".

So after dig in a bit more, I was able to catch the exception:

{System.Threading.Tasks.TaskCanceledException: A task was canceled.
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00026] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Net.Http.HttpClientHandler+<SendAsync>d__63.MoveNext () [0x004c6] in <b696532a7c264e5e866cb15a1b40a4a4>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <b696532a7c264e5e866cb15a1b40a4a4>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0001a] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <3fd174ff54b146228c505f23cf75ce71>:0 
  at AppX.WebServiceCalls+<SendRequestAsync>d__3.MoveNext () [0x000ba] in C:\Users\Bruno\documents\visual studio 2017\Projects\AppX\AppX\AppX\clWebServiceCalls.cs:123 }

I found this guys talking about something similar to it: https://github.com/dotnet/corefx/issues/25800

So far, no clue for the solution.

It seems you are in deadlock because of

HttpResponseMessage response = client.PostAsync(RequestUri(), content).Result;

You should use await for async methods. So, modify that line;

HttpResponseMessage response = await client.PostAsync(RequestUri(), content);

Solution: var client = new HttpClient(new NativeMessageHandler());

This is all code I had to change new NativeMessageHandler() .

I also added a package to my solution. Search for "modernhttpclient".

Thanks everybody for help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM