c#抓住空Json / 404错误

时间:2015-04-03 12:21:16

标签: c# json http-status-code-404

我有以下代码用于访问返回Json值的Api。现在我有可能尝试访问api,但没有任何东西被返回,也就是它试图搜索的给定ID不存在。这个当然会返回404,但我不知道如何处理这个错误,所以代码一直在继续,现在它打破了程序并崩溃。

public RootObject GetApi(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 ex){
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream()){
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

这是按钮点击事件,其中给出了api的URL。

 private void button1_Click(object sender, EventArgs e)
        {
            result_rTBox.Text = "";
            api_Handler api_Handler = new api_Handler();

            string spidyApi_itemSearch = "http://www.gw2spidy.com/api/v0.9/json/item-search/";
            string Gw2Api_allListings = "https://api.guildwars2.com/v2/commerce/listings/";


            string userInput_itemName = userSearchInput_tBox.Text;
            string spidyApi_searchIdByName = spidyApi_itemSearch + userInput_itemName;

            if (!string.IsNullOrWhiteSpace(userSearchInput_tBox.Text)){
                var spidyApi_searchIdByName_result = api_Handler.GetApi(spidyApi_searchIdByName);
                var Gw2Api_isItemIdinListing_result = api_Handler.GetApi(Gw2Api_allListings + spidyApi_searchIdByName_result.results[0].data_id);

                //result_rTBox.Text = Gw2Api_isItemIdinListing_result.results[0].data_id.ToString();
            }
}

首先,我使用字符串“spidApi_itemSearch”访问api,之后我需要检查是否存在于api Gw2Api_allListings中。如果它不存在,这将经常发生,它不返回任何404错误。即使没有返回任何内容,我如何解决代码仍然继续?

编辑:我现在拥有的代码,在休息时仍然崩溃。

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

            try
            {
                var requesting = WebRequest.Create(url);
                using (var response = request.GetResponse())
                {
                    using (var 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 ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError &&
                    ex.Response != null)
                {
                    var resp = (HttpWebResponse)ex.Response;
                    if (resp.StatusCode == HttpStatusCode.NotFound){

                    }

                }
                throw;
            }
        }

1 个答案:

答案 0 :(得分:1)

使用HttpStatusCode Enumeration,特别是HttpStatusCode.NotFound

而不是WebResponse,请尝试使用HttpWebResponse

HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
  // handle the error here
}

我们是WebException