Return of request status code

Asked

Viewed 588 times

0

I’m doing a post for a third party API but would like to get the return code from it to save in our bank, however, I can only get this return code if the code is 202, if it was 401 or 500 it returns me null, i need to return any return code and not null.

public static RetornoRequisicao HttpRequestJson(string token, string url, string dados)
    {

        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Headers.Add("Authorization", token);
        string retorno;
        int status;
        try
        {
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {

                string json = dados;

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)request.GetResponse();

                status = (int)httpResponse.StatusCode;

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    retorno = streamReader.ReadToEnd();
                }
            }

            return new RetornoRequisicao
            {
                retorno = retorno,
                status = status
            };
        }
        catch (Exception e)
        {
            return null;
        }

    }

3 answers

0

If you cannot have a null value there, associate it to some number using the ternary operator ?:.

            ...
            var httpResponse = (HttpWebResponse)request.GetResponse();

            status = (httpResponse != null ? (int)httpResponse.StatusCode : 500);

            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                retorno = streamReader.ReadToEnd();
            ...

Thus, if request.GetResponse() for null, will be admitted (int)500 in his stead in status.

  • this would be a "good" alternative but would be gambiarrada, my intention is to bring really the status code and not a random code, I got null with code 500, but could give 404, 401 and etc..

  • I made a code that returns a random status because you specified in your question: i need to return any return code and not null.

0

When the server returns an error, such as 500, an exception of the Webexception type is thrown. Then to get the error code use a Try/catch. Example:

using System;
using System.Net;

public class Program
{
    public static void Main()
    {
        // Vai retornar um erro 500
        var url = "http://www.mocky.io/v2/5d8d0b982e0000db0dabde95";

        WebRequest request = WebRequest.Create(url);
        request.Method = "get";
        request.ContentType = "application/json";

        try 
        {
            var response = (HttpWebResponse) request.GetResponse();
            Console.WriteLine(response.StatusCode);
        }
        catch (WebException ex)
        {
            // Vai printar ProtocolError neste exemplo
            Console.WriteLine(ex.Status);
        }
    }
}

Documentation link

The Webrequest class throws a Webexception when errors occur while accessing an Internet Resource. The Status Property is one of the Webexceptionstatus values that indicates the source of the error. When Status is Webexceptionstatus.Protocolerror, the Response Property contains the Webresponse Received from the Internet Resource.

  • Just put ex. Status not solved, I found a better solution on the internet that uses this line -> (int)((Httpwebresponse)ex.Response). Statuscode;

0


Solution ->

    public static RetornoRequisicao HttpRequestJson(string token, string url, string dados)
    {

        WebRequest request = WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.Headers.Add("Authorization", token);
        string retorno;
        int status;
        try
        {
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {

                string json = dados;

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)request.GetResponse();

                status = (int)httpResponse.StatusCode;

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    retorno = streamReader.ReadToEnd();
                }
            }
        }
        catch (WebException ex)
        {
            retorno = "Erro ao enviar Json";
            status = (int)((HttpWebResponse)ex.Response).StatusCode;
        }

        return new RetornoRequisicao
        {
            retorno = retorno,
            status = status
        };

    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.