Forum Xamarin.Forms

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

Xamrin form issue with HTTPS request

I have created an application in Xamrin forms with Visual studio 2017 Professional and Visual studio 2019 cumulative addition.

Problem is that app works fine with HTTP request, but in case of HTTPS request i have got time out every time with visual studio 2017 & with visual studio 2019 i have observed sometime getting response of request and sometime app not able to hit HTTPS request.

I have same code to call API. I am able to post WEB API with Postman every time successfully.

        HttpStatusCode = HttpStatusCode.Unused;
        HttpStatusCodeDescription = String.Empty;

        var response = default(TResp);
        XStatusCode = null;

        HttpWebRequest webRequest = null;
        HttpWebResponse webResponse = null;

        webRequest = (HttpWebRequest)WebRequest.Create(mServiceUrl + serviceName);

        webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)));

        webRequest.Method = "POST";



        var reqData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request));

        webRequest.ContentLength = reqData.Length;
        webRequest.ContentType = "application/json; charset=utf-8";
         using (var reqStream = webRequest.GetRequestStream())
            reqStream.Write(reqData, 0, reqData.Length);

        try
        {
            using (webResponse = (HttpWebResponse)webRequest.GetResponse())
            {
                if (typeof(TResp) != typeof(object))
                {
                    using (var respStream = webResponse.GetResponseStream())
                    {
                        var reader = new StreamReader(respStream);
                        string result = reader.ReadToEnd();
                        response = JsonConvert.DeserializeObject<TResp>(result);
                    }
                }

                HttpStatusCode = webResponse.StatusCode;
                HttpStatusCodeDescription = webResponse.StatusDescription;
            }
        }
        catch (WebException ex)
        {
            webResponse = (HttpWebResponse)ex.Response;
            if (webResponse != null)
            {
                HttpStatusCode = ((HttpWebResponse)webResponse).StatusCode;
                HttpStatusCodeDescription = ((HttpWebResponse)webResponse).StatusDescription;
                if (webResponse.Headers["X-StatusCode"] != null)
                {
                    XStatusCode = int.Parse(webResponse.Headers["X-StatusCode"]);
                    if (webResponse.ContentLength > 0)
                    {
                        if (typeof(TResp) != typeof(object))
                        {
                            using (var respStream = webResponse.GetResponseStream())
                            {
                                var reader = new StreamReader(respStream);
                                string result = reader.ReadToEnd();
                                response = JsonConvert.DeserializeObject<TResp>(result);
                            }
                        }
                    }
                }
                webResponse.Close();
            }
        }

        return response;

Tried out with Http Client also getting same result

HttpStatusCode = HttpStatusCode.Unused;
HttpStatusCodeDescription = String.Empty;

        var result = default(TResp);
        XStatusCode = null;




        try
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password)));

            var json = JsonConvert.SerializeObject(request);
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            var response = await client.PostAsync(mServiceUrl + serviceName, content);


            if (response.IsSuccessStatusCode)
            {
                result = JsonConvert.DeserializeObject<TResp>(response.Content.ToString());
            }

        }
        catch (WebException ex)
        {
            var webResponse = (HttpWebResponse)ex.Response;
            if (webResponse != null)
            {
                HttpStatusCode = ((HttpWebResponse)webResponse).StatusCode;
                HttpStatusCodeDescription = ((HttpWebResponse)webResponse).StatusDescription;
                if (webResponse.Headers["X-StatusCode"] != null)
                {
                    XStatusCode = int.Parse(webResponse.Headers["X-StatusCode"]);
                    if (webResponse.ContentLength > 0)
                    {
                        if (typeof(TResp) != typeof(object))
                        {
                            using (var respStream = webResponse.GetResponseStream())
                            {
                                var reader = new StreamReader(respStream);
                                string resulttmp = reader.ReadToEnd();
                                result = JsonConvert.DeserializeObject<TResp>(resulttmp);
                            }
                        }
                    }
                }
                webResponse.Close();
            }
        }



        return result;

PCL package

Android package

Best Answer

  • George_LeitheadGeorge_Leithead Member ✭✭
    Accepted Answer

    Have you tried adding the correct headers?

                client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "HelloWorld.MyApp");
                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, targetUri);
                HttpResponseMessage response = await client.SendAsync(requestMessage).ConfigureAwait(false);
    
    

Answers

  • navneet567navneet567 Member ✭✭

    Is xamrin .forms support https request or not other application works fine with same code but getting issue with xamrin.
    I am going with xamrin in my case or i deny it, i have purchased license of visual studio professional 2017, but not able to deliver app with https in xamrin.

    Please clear the answer of my question.

  • LandLuLandLu Member, Xamarin Team Xamurai

    Try to create a new blank application with Visual Studio 2019.
    The latest release Forms version has come to 4.6:
    https://docs.microsoft.com/en-us/xamarin/xamarin-forms/release-notes/4.6/4.6.0
    Some features on Visual Studio can't be used especially for iOS.
    And https doesn't need any extra configuration.
    I highly recommend migrating from 2017 to 2019.

  • navneet567navneet567 Member ✭✭

    After update xamrin forms to 4.6 getting less timeout, why getting timeout?

  • navneet567navneet567 Member ✭✭

    After updating xamrin.forms getting sometime timeout request dose not reach to the web server and sometime it works.

  • LandLuLandLu Member, Xamarin Team Xamurai

    Is your webservice stable to send data?
    Have you tried to test this with other https servers?
    Google rest API sample:

    And test this sample web:
    https://reqres.in/api/users?page=2

  • navneet567navneet567 Member ✭✭

    Hi Thanks for reply,

    When i used your URL then i am able to get response perfectly, but in my case when i capture traffic at fidler then it showing http protocol instead of https.

    Any help why my URL going to connect with http.

  • LandLuLandLu Member, Xamarin Team Xamurai

    If other https requests went through successfully, the issue could be caused by your server side.
    Did your backend service implement the https?
    Did it use a self-signed certificate?

  • navneet567navneet567 Member ✭✭

    I have used same service for ..net website it working fine but problem receive at mobile, is we need to add some extra header.
    Because my service support tls 1.2.
    I have recently observed some issue like...
    When i have attached fiddler and track mobile trafic it worked and get response when i have closed fiddler after getting same problem.
    Is that Xamrin/ code side issue or network side issue?

    Because everything works fine with postman and other.

  • LandLuLandLu Member, Xamarin Team Xamurai

    I guess this may be your connection issue.
    You've tested the https request I provided above and got the expected result. This means we could exclude the Xamarin part.

  • navneet567navneet567 Member ✭✭

    Working fine with your HTTPS request, found two issue observed one of missing network config file missing in android app and second network side some DNS related entry missing, but same problem occurred in IOS not able to hit Https request.
    Even after define ATS.

  • LandLuLandLu Member, Xamarin Team Xamurai

    iOS supports https by default. And Apple even suggests doing this.
    If the issue only occurs with this particular rest api.
    I have to say it may be caused by the server part.

  • navneet567navneet567 Member ✭✭

    Below simple get request not working ...both android and IOS . i have also checked with http it not working.
    using (var client = new HttpClient())
    {
    try
    {

                var response1 = await client.GetStringAsync("https://reqres.in/api/users?page=2");
    
            }
            catch (WebException ex)
            {
    
            }
        }
    

    please check below for more details
    https://stackoverflow.com/questions/62610790/xamarin-forms-get-request-not-working-for-http-and-https

  • George_LeitheadGeorge_Leithead Member ✭✭
    Accepted Answer

    Have you tried adding the correct headers?

                client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "HelloWorld.MyApp");
                HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, targetUri);
                HttpResponseMessage response = await client.SendAsync(requestMessage).ConfigureAwait(false);
    
    
  • George_LeitheadGeorge_Leithead Member ✭✭

    Also, do you have a PROXY in the way? Further, have you set the security authentication protocols and a ServerCertificateValidationCallback handler?

Sign In or Register to comment.