Dheeraj_Vashist
Dheeraj_Vashist

Reputation: 79

How to use HttpWebRequest with async & await

I am new to Xamarin and C# as well. I try to make a Http request to my server with some information. In general with android Native a uses AsyncTask and HttpClient for that. and build a json object or name value pair, and encrypt it to integrate information with the request. But when I try to do the same with xamarin I get some problems.

  1. if I try to import the namespace

using System.Net.Http.HttpClient than my xamarin not have this namespace

  1. Because of the above problem I try to use HttpWebRequest. But when I go for use it with the asyc and await I am not getting any response from server.

I am new to xamarin so I am not sure about async and await keyword. I read lot of articles but No luck :(

on Click of the Button I call the below Method

 public async Task<int> ValidateUser(){
    try{
     var request = HttpWebRequest.Create (URL);
     request.Method = "GET/POST";
     String postString = String.Format ("AAA ={0}&BBB={1}&CCC={2}", "111", 
                                          "222","333");

        byte[] postByte = Encoding.UTF8.GetBytes (postString);

        Stream st = request.GetRequestStream ();

        //I am reaching here
            Console.WriteLine("Check for Validity");

        request.ContentLength = postByte.Length;

        st.Write (postByte, 0, postByte.Length);

        st.Close ();
            Task<Stream> contentTask = request.GetRequestStreamAsync();
            Stream response = await contentTask;

            String str = response.ToString();

            // this is not getting printed in Console 
               Console.WriteLine("=====>>"+str);

      }
        catch (WebException exception) {
            string responseText;
            using (var reader = new StreamReader(exception.Response.GetResponseStream())) {
                responseText = reader.ReadToEnd ();
                Console.WriteLine ("====Dude Error"+responseText);
            }
        }catch(Exception e){

        }
        return 1;
    }

Any help will be appreciated

Upvotes: 0

Views: 2170

Answers (2)

Chris
Chris

Reputation: 3338

Consider using RestSharp, a component created for Xamarin to facilitate web requests. Click here for more info on the component. It will facilitate allot of things about webrequesting ( like serialization, automatic return type detection,... )

Your code would look something like this with restsharp:

public async Task<int> ValidateUser(){

     var client = RestClient (URL);
     var request = new RestRequest ("AAA ={0}&BBB={1}&CCC={2}", "111", 
                                          "222","333");

            client.ExecuteAsync (request, response => {

                    WebApiResponse webApiResponse = new WebApiResponse ();

                    webApiResponse.Content = response.Content;
                    webApiResponse.StatusCode = response.StatusCode;
                    webApiResponse.ResponseStatus = (WebApiResponseStatus)response.ResponseStatus;

                    return webApiResponse.Content;
                });         


        return -1

    }

Upvotes: 2

Frank
Frank

Reputation: 733

Using HttpWebRequest is a bad idea, instead it would be better to focus on why you don't have the System.Net.Http.* namespace. Imho the most likely cause is that you didn't add System.Net.Http as a reference to your project.

Here's how you add System.Net.Http.* to your project.

In Visual Studio 2013:

  • Open the solution
  • Open the project
  • Open the Solution Explorer
  • Right-click on References
  • Add Reference
  • Click on 'Search Assemblies'
  • Type in 'Http'
  • Select System.Net.Http
  • Press 'OK'

In Xamarin Studio:

  • Open the solution
  • Open the project
  • Open the Solution Explorer
  • Right-click on References
  • Edit References
  • Type in 'Http'
  • Select System.Net.Http
  • Press 'OK'

Afterwards there should be no problems resolving System.Net.Http when 'using System.Net.Http;'

Upvotes: 0

Related Questions