简体   繁体   中英

c# HttpWebRequest 404, return null on object not entire List

I have a code that retrieves Json value from a Api link. This is deserialized and stored as object in a list. The ID values in this list are then used to retrieve other Json values from a different Api link. Only these Id's have a possibility to not exist in the second Api link. If this is the case all that is shown is {"text":"no such id"} and the program crashes with a 404 error.

This is the code:

public RootObject objFromApi_idExistListings(string url)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    var jsonReader = new JsonTextReader(reader);
                    var serializer = new JsonSerializer();
                    return serializer.Deserialize<RootObject>(jsonReader);
                }
            }
            catch (WebException)
            {
                return null;
            }
        }

When a 404 is hit it returns everything null from there on. Not only that single Api request and then continues, no the entire list is then returned null.

How do i get around to only make that object return null and everything else continues. Or how do i skip the entire making of that object when its a 404, doesnt have to be returned null as long as the code can continue going and deserialize all left Api links it has to work through.

You could use something like this to bail out if there is a 404 response (or any response other than 200).

try
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode != System.Net.HttpStatusCode.OK) return null;
    //Continue by getting and parsing the response stream

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