无法下载Json Array Windows手机

时间:2013-05-04 07:43:38

标签: c# windows-phone-8 httpclient webclient

我可以使用以下代码在Windows 8中下载Json数组:

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

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

这100%

我试图在Windows手机中使用此

进行相同的操作
        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;
}

这不起作用,我收到了这个例外:

  

类型'System.Reflection.TargetInvocationException'的异常   发生在System.ni.dll中但未在用户代码中处理

进入内部异常我看到了:

  

InnerException {System.Net.WebException:远程服务器返回错误:NotFound。 ---> System.Net.WebException:远程服务器返回错误:NotFound。

以下完全例外。

修改 Windows Phone无法使用HttpClient类。我按照互联网的建议选择了WebClient。打开其他选项。 await方法似乎不起作用,WebClient必须称为Async。我认为这可能与我将字符串转换为URI有关。遗憾的是,网址尚未公开,但这里的网址类似于网址。

为了清晰而编辑......

> -     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 个答案:

答案 0 :(得分:3)

您应该使用DownloadStringTaskAsync而不是DownloadStringAsync - 此时您将能够等待结果,尽管只能使用异步方法。编辑:我认为WP8上可以使用,但显然不是。

如果您想在Windows Phone应用中使用HttpClient,可以使用Microsoft.Net.Http NuGet包。

(你可以使用DownloadStringAsync,这是使用WebClient的“旧”方式,但是你需要订阅相应的事件。使用async /等待更清洁。)

答案 1 :(得分:1)

您可以编写一个类似于Jon DownloadStringTaskAsync Jon Skeet建议的函数。

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;
    }
}