Can't call old webservice in xamarin Android with HTTPClient

萝らか妹 提交于 2019-12-11 16:16:08

问题


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();

来源:https://stackoverflow.com/questions/54205419/cant-call-old-webservice-in-xamarin-android-with-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!