Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

HttpWebRequest / HttpClient wont post

RexHopeRexHope PHMember ✭✭
edited June 2017 in Xamarin.Forms

` public async Task ValidateUser(string username, string password)
{
//Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var m = new UserModel
        {
            user = new List<user>
            {
                new user{username = username, password=password}
            }

        };



        var Sercontent = JsonConvert.SerializeObject(m);
        //var content = new StringContent(Sercontent, Encoding.UTF8, "application/json");

        //var response = await Client.PostAsync(URL, content).ConfigureAwait(false); //breaks here
        //if (response.IsSuccessStatusCode)
        //    return await response.Content.ReadAsStringAsync();
        //return null;

        var http = (HttpWebRequest)WebRequest.Create(new Uri(URL2));
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";

        UTF8Encoding enc = new UTF8Encoding();
        Byte[] bytes = enc.GetBytes(Sercontent);

        using (var stream = await Task.Factory.FromAsync<Stream>(http.BeginGetRequestStream, http.EndGetRequestStream, null)) //breaks here
        {
            stream.Write(bytes, 0, bytes.Length);
            stream.Dispose();
        }


        using (var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(http.BeginGetResponse‌​, http.EndGetResponse, null))
        {
            var responseStream = response.GetResponseStream();
            var sr = new StreamReader(responseStream);
            var content = sr.ReadToEnd();
            return content;
        }

}`

The app gets unhandled exception, idk why, I have tried this using console app and it works magically, only using xamarin forms makes it hard.
I am also using .svc as web service but yea we treat it as http web.

Best Answer

  • RexHopeRexHope PHMember ✭✭
    Accepted Answer

    Fixed. The webservice I tried to fetch is not accessible through mobile/emulator, also I did not use httpclient for this (it doesn't work in my case) but rather I used HttpWebRequest.

Answers

  • RexHopeRexHope PHMember ✭✭
    Accepted Answer

    Fixed. The webservice I tried to fetch is not accessible through mobile/emulator, also I did not use httpclient for this (it doesn't work in my case) but rather I used HttpWebRequest.

Sign In or Register to comment.