locked
HttpClient for Windows Phone 8 RRS feed

  • Question

  • Hi,

    I am converting a Windows 8 store application (WinRT, C#, XAML) to Windows Phone 8.

    I am trying to use a routine from my Windows 8 application to send HTTP Client Request:

            public async Task SendHttpClientRequest( Uri uri )
                {
                try
                    {
                    HttpClient client = new HttpClient();
                    HttpResponseMessage response = await client.GetAsync( uri );
                    response.EnsureSuccessStatusCode();
                    string responseBody = string.Empty;
                    responseBody = await response.Content.ReadAsStringAsync();
                    }
                catch ( HttpRequestException e )
                    {
                    Debug.WriteLine( "\nException Message :{0} ", e.Message );
                    }
                }

    However when using this code in Windows Phone 8 application, VS2012 does not recognize the HttpClient. According to the documentation the assembly should be System.Net.Http.dll however defining:

    using System.Net.Http;

    is not defined and creates error.

    In the project References, I am using ".NET for Windows Phone" and "Windows Phone".

    When searching for HttpClient in the Online Help:

    http://social.msdn.microsoft.com/Search/en-US/windowsphone?query=httpclient&Refinement=184&ac=1

    The links in the above web page lead to Windows 8 store application examples?!

    What am I missing here?

    Thanks,
    EitanB



    • Edited by eitanb Saturday, February 23, 2013 8:22 AM
    Saturday, February 23, 2013 8:20 AM

Answers

  • Got it to work with HttpWebRequest.

    Apparently the portable HttpClient is not "there" yet (It was crushing sometimes on the Phone).

    The new code is:

            private SynchronizationContext _context;
            public event EventHandler<ErrorEventArgs> Error;
    

            public void SendHttpClientRequest( Uri uri, string username, string password )
                {
                try
                    {
                    HttpWebRequest.RegisterPrefix( "http://", WebRequestCreator.ClientHttp );
                    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create( uri );
                    if ( !string.IsNullOrEmpty( username ) || !string.IsNullOrEmpty( password ) )
                        {
                        httpWebRequest.Credentials = new NetworkCredential( username, password );
                        }
    
                    // start the stream immediately
                    httpWebRequest.AllowReadStreamBuffering = false;
    
                    // asynchronously get a response
                    httpWebRequest.BeginGetResponse( ResponseCallback, httpWebRequest );
                    }
                catch ( HttpRequestException e )
                    {
                    Debug.WriteLine( "\nException Message :{0} ", e.Message );
                    }
                }
    
            private void ResponseCallback( IAsyncResult asyncResult )
                {
                char[ ] Buffer = new char[ 1024 ];
    
                // get the response
                HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse httpWebResponse = null;
                try
                    {
                    httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse( asyncResult );
    
                    Stream responseStream = httpWebResponse.GetResponseStream();
                    BinaryReader binaryReader = new BinaryReader( responseStream );
    
                    Buffer = binaryReader.ReadChars( Buffer.Length );
    
                    httpWebResponse.Close();
                    }
                catch ( Exception ex )
                    {
                    if ( Error != null )
                        _context.Post( delegate { Error( this, new ErrorEventArgs() { Message = ex.Message } ); }, null );
    
                    return;
                    }
                }
    

    Seems to work more reliably like this.

    EitanB

    • Marked as answer by eitanb Saturday, February 23, 2013 11:10 PM
    Saturday, February 23, 2013 11:10 PM

All replies

  • You should be using HttpWebRequest for the windows phone

    http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

    Saturday, February 23, 2013 9:16 AM
  • Hi,

    Microsoft has what they call a

    Portable HttpClient for .NET Framework and Windows Phone

    The last version of it was published on 2/18/2013 and it should be included in the project using the NuGet package manager.

    The following link describes it:

    http://blogs.msdn.com/b/bclteam/archive/2013/02/18/portable-httpclient-for-net-framework-and-windows-phone.aspx

    Installed it and

    using System.Net.Http;

    Is now recognized.

    Thanks
    EitanB

    Saturday, February 23, 2013 9:32 AM
  • Hi Ken,

    Just for my knowledge, how would you convert the function above to use HttpWebRequest?

    From reading about HttpWebRequest I understand that I have to specify a callback function to handle the data returned?

    Thanks,
    EitanB


    • Edited by eitanb Saturday, February 23, 2013 10:05 AM
    Saturday, February 23, 2013 9:42 AM
  • Got it to work with HttpWebRequest.

    Apparently the portable HttpClient is not "there" yet (It was crushing sometimes on the Phone).

    The new code is:

            private SynchronizationContext _context;
            public event EventHandler<ErrorEventArgs> Error;
    

            public void SendHttpClientRequest( Uri uri, string username, string password )
                {
                try
                    {
                    HttpWebRequest.RegisterPrefix( "http://", WebRequestCreator.ClientHttp );
                    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create( uri );
                    if ( !string.IsNullOrEmpty( username ) || !string.IsNullOrEmpty( password ) )
                        {
                        httpWebRequest.Credentials = new NetworkCredential( username, password );
                        }
    
                    // start the stream immediately
                    httpWebRequest.AllowReadStreamBuffering = false;
    
                    // asynchronously get a response
                    httpWebRequest.BeginGetResponse( ResponseCallback, httpWebRequest );
                    }
                catch ( HttpRequestException e )
                    {
                    Debug.WriteLine( "\nException Message :{0} ", e.Message );
                    }
                }
    
            private void ResponseCallback( IAsyncResult asyncResult )
                {
                char[ ] Buffer = new char[ 1024 ];
    
                // get the response
                HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
                HttpWebResponse httpWebResponse = null;
                try
                    {
                    httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse( asyncResult );
    
                    Stream responseStream = httpWebResponse.GetResponseStream();
                    BinaryReader binaryReader = new BinaryReader( responseStream );
    
                    Buffer = binaryReader.ReadChars( Buffer.Length );
    
                    httpWebResponse.Close();
                    }
                catch ( Exception ex )
                    {
                    if ( Error != null )
                        _context.Post( delegate { Error( this, new ErrorEventArgs() { Message = ex.Message } ); }, null );
    
                    return;
                    }
                }
    

    Seems to work more reliably like this.

    EitanB

    • Marked as answer by eitanb Saturday, February 23, 2013 11:10 PM
    Saturday, February 23, 2013 11:10 PM
  • You should use nuget and get the microsoft httpclient as eitanb states in a post rather than his accepted answer.
    Your http client code would work direct out of the box.

    The search name is "Microsoft Http Client Libraries", it will also install the BCL libraries.


    • Edited by Choco_Smith Monday, July 29, 2013 12:15 PM correction
    Monday, July 29, 2013 12:10 PM