3

I have a API which returns the json response. When I call the API from Fiddler it gives me the json reponse as shown below:

enter image description here

JSON Response: enter image description here

Call to API from Web page:

protected void FinalCall()
    {

       // try
       // {
            string url = txtdomainURL.Text.Trim(); 
            string apiname = txtAPIname.Text.Trim();
            string apiURL = apiname+"/"+txtStoreID.Text.Trim()+"/"+txtSerialNo.Text.Trim(); //"duediligence/1/45523354232323424";// 990000552672620";//45523354232323424";
            //duediligence/1/45523354232323424 HTTP/1.1
            string storeID = txtStoreID.Text.Trim();//Test Store ID:1 Live Store ID: 2
            string partnerID = txtPartnerID.Text.Trim();// "1";
            string scretKey = txtSecretKey.Text.Trim();// "234623ger787qws3423";
            string requestBody = txtRequestBody.Text.Trim(); //"{\"category\": 8}";
            string data = scretKey + requestBody;


            string signatureHash = SHA1HashStringForUTF8String(data);
            lblSignatureHash.Text = signatureHash;
            String userName = partnerID;
            String passWord = signatureHash;
            string credentials = userName + ":" + passWord;//Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
            var dataString = JsonConvert.SerializeObject(requestBody); //JsonConvert.SerializeObject(requestBody);
            var bytes = Encoding.Default.GetBytes(dataString);


            WebClient client = new WebClient();
            string base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
            client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
            lblBase64.Text = base64;

            client.Headers.Add(HttpRequestHeader.Accept, "application/json");
            client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
            //string response = cli.UploadString(url + apiURL, dataString); //"{some:\"json data\"}"
            string completeURLRequest = url + apiURL;

            //I GET ERROR HERE 
            var result = client.DownloadString(completeURLRequest);
            //CODE below this line is not executed

            //Context.Response.TrySkipIisCustomErrors = true;
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var jsonObject = serializer.DeserializeObject(result.ToString());
            //var result1 = client.UploadData(completeURLRequest, "POST", bytes);
            Response.Write(result);
            txtwebresponse.Text = jsonObject.ToString();
        //}

Now, When the same is executed from a web page it throws exeception '401 Unauthorized Exception'. So, instead of showing error page I want to read the returned JSON error response (as in fiddler) and show to user.

Help Appreciated!

SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143
  • http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba – SilentTremor Jul 29 '15 at 07:10
  • hi @SilentTremor, thanks for the reply. It worked perfectly..! please post it as answer to get points/upvotes..! :) – SHEKHAR SHETE Jul 29 '15 at 07:19
  • `401` isn't an exception, it's a cchallange in response to an `Unauthorized` request. – Amit Kumar Ghosh Jul 29 '15 at 07:21
  • Possible duplicate of [.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned](https://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba) – Wai Ha Lee Jan 07 '19 at 15:38

2 Answers2

13

Adapted from this answer to ".Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned" by Jon Skeet:

try
{
    using (WebResponse response = request.GetResponse())
    {
        Console.WriteLine("You will get error, if not do the proper processing");
    }
}
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse) response;
        Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
        using (Stream data = response.GetResponseStream())
        using (var reader = new StreamReader(data))
        {
            // text is the response body
            string text = reader.ReadToEnd();
        }
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
SilentTremor
  • 4,747
  • 2
  • 21
  • 34
0

Slightly changing SilentTremor's answer. Combining the using statements makes the code a little bit shorter.

 catch (WebException ex)
 {
            HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
            using (WebResponse response = ex.Response)
            using (Stream data = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(data))
            {
                string errorMessage = reader.ReadToEnd();
            }
 }
Robert Stokes
  • 335
  • 4
  • 7