简体   繁体   中英

Async web service call not getting data

I have the following code for my generic class. This can be used for any of the classes that I pass into the method.

public static async Task<T>GetData<T>(string req, bool weather = false)
    {
        string webrequest = string.Format("{0}&{1}", req, !weather ? string.Format("key={0}", MainClass.GoogleAPI) : string.Format("APPID={0}", MainClass.WeatherID));
        var request = WebRequest.Create(webrequest) as HttpWebRequest;
        request.Method = "GET";
        request.Accept = "application/json";
        request.ContentType = "application/json";
        string responseContent = "";

        T obj = Activator.CreateInstance<T>();

        try
        {
            var asyncResult = request.BeginGetResponse(new AsyncCallback(s =>
                    {
                        var response = (s.AsyncState as WebRequest).EndGetResponse(s);

                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            responseContent = reader.ReadToEnd();
                            obj = GeneralUtils.Deserialize<T>(responseContent);
                        }

                }), request);
            return obj;
        }
        catch (WebException ex)
        {
            Debug.WriteLine("Deserialiser failed : {0}--{1}", ex.StackTrace, ex.Message);
            return default(T);
        }
    }

The request string contains the likes of this

var servercall = "https://maps.googleapis.com/maps/api/directions/json?origin=Warrington,UK&destination=Whiston,UK&waypoints=Preston,UK|Dundee,UK";

the API key is fine.

What I'm finding is that the response line within the asyncResult is never being hit so just the class being passed in is being returned. The classes are generated using the jsontocsharp website using the examples on the google API website.

Normally, I would not use this code, but this is for a PCL library, so needs to be done this way (unless there is another way to do this synchronously that is).

I am not using JSON.Net for this (application spec forbids anything not part of standard .NET). The tests are running as a console app.

Your method does not await a response from BeginGetResponse , so it ends straightaway and returns obj that is an empty object.

There are many ways of doing this, this is one of them:

public static async Task<T> GetData<T>(string req, bool weather = false)
{
    string webrequest = string.Format("{0}&{1}", req, !weather ? string.Format("key={0}", MainClass.GoogleAPI) : string.Format("APPID={0}", MainClass.WeatherID));
    var request = WebRequest.Create(webrequest) as HttpWebRequest;
    request.Method = "GET";
    request.Accept = "application/json";
    request.ContentType = "application/json";
    try
    {
       var response = await request.GetResponseAsync();

       using (var reader = new StreamReader(response.GetResponseStream()))
          return GeneralUtils.Deserialize<T>(reader.ReadToEnd());
    }
    catch (Exception ex)
    {
       Debug.WriteLine("Deserialiser failed : {0}--{1}", ex.StackTrace, ex.Message);
       throw;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM