locked
Net.Web Exception while fetching Data from API RRS feed

  • Question

  • Hi Friends, 

    I am making windows phone 8 application and in that i am trying to fetch data from server using API. API returns JSON and that JSON I am mapping to C# class. I am calling api with asynchronous httpwebrequest..

    But  the code I am using sometimes suddenly crashes my application and nothing works...and I am not able to figure out why it is crashing sometime... How to catch Exception in asynchronous? it is tedious . 

    Code for Getting Data and posting is here... Both are crashing sometimes and Excetion is comming at line  asyncResult => request.EndGetResponse(asyncResult)

    Exception:'System.Net.WebException' occurred in System.Windows.ni.dll 

    Is anybody have solution? , please reply

    Thank U 


           

    Code for Get Data



      class ApiConnection<T> where T : class //T is C# class For JSON data
        {

          private readonly string _url;
            CookieContainer cookieJar = new CookieContainer();

            public ApiConnection(string url)
            {
                _url = url;
            }


            public async Task<T> GetResult()
            {

                var response = await MakeAsyncRequest(_url);
                var result = JsonConvert.DeserializeObject<T>(response);
                return result;
            }

            public Task<string> MakeAsyncRequest(string url)
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                if (PostDataAPIConnection.isCookie == 1)
                {
                    request.CookieContainer = cookieJar;
                    foreach (Cookie cookie in PostDataAPIConnection.responseCookies)
                    {
                        System.Diagnostics.Debugger.Log(1, "", "" + cookie.Name);
                        //request.CookieContainer.Add(new Uri(cookie.Name), cookie);
                    }
                }

                try
                {

                    Task<WebResponse> task = Task.Factory.FromAsync(
                        request.BeginGetResponse,
                        asyncResult => request.EndGetResponse(asyncResult),
                        null);
                    return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debugger.Log(1, "", "Network problem :" + ex.Response);
                    throw ex;
                    // return "";

                }


            }

            private static string ReadStreamFromResponse(WebResponse response)
            {
                using (var responseStream = response.GetResponseStream())
                using (var reader = new StreamReader(responseStream))
                {
                    var content = reader.ReadToEnd();
                    return content;
                }
            }
        }
    }

            
     

    Code for Post Data

    class PostDataAPIConnection { static string data; static string url; public static int isCookie; public static CookieContainer cookieJar = new CookieContainer(); public static CookieCollection responseCookies = new CookieCollection(); public PostDataAPIConnection() { data = ""; url = ""; isCookie = 0; } public static ManualResetEvent allDone = new ManualResetEvent(false); public async Task<string> PostData(string data1, string url1) { data = data1; url = url1; var response = await MakeAsyncRequest(); var result = response as string; return result; } public Task<string> MakeAsyncRequest() {

    //Create a new HttpWebRequest object. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookieJar; // Set the ContentType property. request.ContentType = "application/json"; // Set the Method property to 'POST' to post data to the URI. request.Method = "POST"; // Start the asynchronous operation. request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request); allDone.WaitOne(); Task<WebResponse> task = Task.Factory.FromAsync( request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), null); // Exception is coming Here... try { if (task.IsFaulted) throw new Exception(); } catch (Exception e) { System.Diagnostics.Debugger.Log(1, "", "Error Occured----->>>>" + e); } Task<string> response = task.ContinueWith(t => { string str = ReadStreamFromResponse(t.Result); var webResponse = t.Result as HttpWebResponse; if (webResponse.Cookies != null && webResponse.Cookies.Count != 0) { responseCookies = webResponse.Cookies; // cookieJar.Add(webResponse.Cookies); isCookie = 1; } return str; } ); return response; } private static string ReadStreamFromResponse(WebResponse response) { using (var responseStream = response.GetResponseStream()) using (var reader = new StreamReader(responseStream)) { var content = reader.ReadToEnd(); return content; } } private static void ReadCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; // End the operation. Stream postStream = request.EndGetRequestStream(asynchronousResult); string postData = data; // Convert the string into a byte array. byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Write to the request stream. postStream.Write(byteArray, 0, postData.Length); postStream.Close(); allDone.Set(); } }







    Tuesday, March 5, 2013 8:02 AM

All replies

  • You need try/catch around the code which is executing asynchronously.  (try/catch around the code which calls the asynchronous operation will only catch exception thrown setting up the operation.)

    -Eric.

    Tuesday, March 5, 2013 7:17 PM
  • Thanks for reply,

    but even I used try catch surrounding asynchronous method calling  i.e. 

    1) Task.Factory.FromAsync(.... and

    2)response = await MakeAsyncRequest(_url);

    but Exception Comes and App crashes .. It doesnt catch 


    Friday, March 8, 2013 12:25 PM
  • The exception is occurring here because the EndGetResponse isn't successful:

     asyncResult => request.EndGetResponse(asyncResult),

    You'll have to add exception handling there.  In this case, the lambda isn't helping you at all - you'll have to actually write a method that gets the response and checks the value (and catches exceptions)


    Darin R.

    Friday, March 8, 2013 2:27 PM