Can't call old webservice in xamarin Android w

2019-08-25 01:28发布

I read a lot of thing on using HTTPClient to communicate with an old webservice. Code are in xamarin Forms with .NetStandard (System.Net.Http) I just have this simple code:

    public async Task<bool> TestKelvinConnectivity()
    {
        bool retour = false;

        using (var client = new HttpClient())
        {
            client.BaseAddress = _baseEnkiWeb;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/soap+xml"));

            string Enveloppe = "<soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:dun='http://Dunin.com'><soap:Header><dun:User></dun:User><dun:ClefSession>Login</dun:ClefSession><dun:Licence1>EnkiEve</dun:Licence1><dun:Licence2></dun:Licence2></soap:Header><soap:Body><dun:loadMaintenance></dun:loadMaintenance></soap:Body></soap:Envelope>";
            var content = new StringContent(Enveloppe, Encoding.UTF8, "application/soap+xml");

            try
            {
                var response = await client.PostAsync(_baseEnkiWeb.ToString(), content);
                var soapResponse = await response.Content.ReadAsStringAsync();

                if (soapResponse.Contains("ErreurAuthentification") == true)
                {
                    throw new Exception("ErreurLoadMaintenance");
                }

                XDocument soap = XDocument.Parse(soapResponse);
                XNamespace ns = "http://Dunin.com";

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        return false;
    }

On UWP the code is working good and I receive the answer after response.Content.ReadAsStringAsync(); But on Android, I can trace the code until the await client.PostAsync(...) then the debugger jump the the "return false" at the end of the function. No exception, no error and the only thing I have in the Android Device Log is: NetworkSecurityConfig: No Network Security Config spécified, using platform default.

Any idea? The URL is local to the developpement computer and accessible from the android simulator device browser.

EDIT1: I can make my code work when I remove the await in front of the PostAsync method and add .Result. But I do not understand why. This code work well for UWP! There is my modification (soapResponse got the correct data):

var response = client.PostAsync(_baseEnkiWeb.ToString(), content).Result;
var soapResponse = await response.Content.ReadAsStringAsync();

0条回答
登录 后发表回答