0
votes

I can download a Json array in Windows 8 with the following code:

aString = "http://website.com/image/image_manifest.json";

private async void GetJSON(string aString)
        {
            var client = new HttpClient();
            var lResponse = await client.GetStringAsync(aString);
}

This works 100%

I am attempting to do the same in Windows phone with this

        private void GetJSON(string aNASAURL)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientHandler);
              webClient.DownloadStringAsync(new Uri(aString));
}
    private void webClientHandler(object sender, DownloadStringCompletedEventArgs e)
        {
            var lResponse = e.Result;
}

This does not work, I receive this exception:

An exception of type 'System.Reflection.TargetInvocationException' occurred in System.ni.dll but was not handled in user code

Going into the inner exception I see this:

InnerException {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.

Full Exception Below.

EDIT: The HttpClient class is not available to windows phone. I chose WebClient as per the interwebs suggestion. Open to other options. The await method doesn't seem to work and WebClient must be called Async. I think that it may have something to do with my conversion of string to URI. Unfortunately the url can't yet be made public but here is a similar url structure as string.

Edited for clarity......

> -     e   {System.Net.DownloadStringCompletedEventArgs}   System.Net.DownloadStringCompletedEventArgs
+       base    {System.Net.DownloadStringCompletedEventArgs}   System.ComponentModel.AsyncCompletedEventArgs {System.Net.DownloadStringCompletedEventArgs}
-       Result  'e.Result' threw an exception of type 'System.Reflection.TargetInvocationException' string {System.Reflection.TargetInvocationException}
-       base    {System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
   at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
   --- End of inner exception stack trace ---
   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at System.Net.DownloadStringCompletedEventArgs.get_Result()} System.Exception {System.Reflection.TargetInvocationException}
+       Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
        HelpLink    null    string
        HResult -2146232828 int
-       InnerException  {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
   at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)}   System.Exception {System.Net.WebException}
+       [System.Net.WebException]   {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
   at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)}   System.Net.WebException
+       Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
        HelpLink    null    string
        HResult -2146233079 int
-       InnerException  {System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)}  System.Exception {System.Net.WebException}
+       [System.Net.WebException]   {System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)}  System.Net.WebException
+       Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
        HelpLink    null    string
        HResult -2146233079 int
+       InnerException  null    System.Exception
        Message "The remote server returned an error: NotFound."    string
        Source  "System.Windows"    string
        StackTrace  "   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)\r\n   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)\r\n   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)"    string
+       Static members      
+       Non-Public members      
        Message "The remote server returned an error: NotFound."    string
        Source  "System.Windows"    string
        StackTrace  "   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)\r\n   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)\r\n   at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)"  string
+       Static members      
+       Non-Public members      
        Message "An exception occurred during the operation, making the result invalid.  Check InnerException for exception details."   string
        Source  "System"    string
        StackTrace  "   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()\r\n   at System.Net.DownloadStringCompletedEventArgs.get_Result()" string
+       Static members      
+       Non-Public members      
2

2 Answers

1
votes

You can write a function similar to DownloadStringTaskAsync Jon Skeet suggested.

WebClient wc = new WebClient();
string result = await wc.DownloadAsync("http://www.stackoverflow.com");

public static partial class MyExtensions
{
    public static Task<string> DownloadAsync(this WebClient wc, string url)
    {
        TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
        DownloadStringCompletedEventHandler completed = null;

        completed = (s, e) =>
        {
            try
            {
                tcs.SetResult(e.Result);
            }
            catch (Exception ex)
            {
                tcs.SetException(ex.InnerException ?? ex);
            }
            finally
            {
                wc.DownloadStringCompleted -= completed;
            }
        };

        wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
        wc.DownloadStringCompleted += completed;
        wc.DownloadStringAsync(new Uri(url));

        return tcs.Task;
    }
}
3
votes

You should be using DownloadStringTaskAsync rather than DownloadStringAsync- at that point you'll be able to await the result, although only in an async method. EDIT: I thought that was available on WP8, but apparently it's not.

If you want to use HttpClient in a Windows Phone app, you can use the Microsoft.Net.Http NuGet package.

(You can use DownloadStringAsync, which is the "old" way of using WebClient, but then you need to subscribe to the appropriate events instead. Using async/await is much cleaner.)