Basic Auth API connection

Asked

Viewed 330 times

1

I need to connect to an API in the HTTP GET METHOD with Basic Auth. I took this example on the net, adjusted but it’s not returning anything.

string username = "179341"; string password = "12CC97";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
            string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
            request.Headers.Add("Authorization", "Basic" + encoded);
            request.ContentType = "application/xml";
            request.Method = "GET";
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            responseStr = new StreamReader(responseStream).ReadToEnd();

inserir a descrição da imagem aqui

Where am I wrong? thanks this already.

  • 1

    I don’t understand C# but looking at your code I already see some things that may have gone wrong, confirm the Method I believe it should be POST, there line where you add the Authorization header between Basic and the encoded string has to have a blank space, then it would be "Basic" + encoded. Try to increase the verbosity level of your log, for sure is returning some error or giving some error, this will help you

1 answer

1


Try it that way:

public string HttpRequest(string url, string username, string password)
    {
        string authInfo = username + ":" + password;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));


        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Accept = "application/json; charset=utf-8";

        request.Headers["Authorization"] = "Basic " + authInfo;

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

        string strResponse = "";
        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            strResponse = sr.ReadToEnd();

        }

        return strResponse;
    }
  • Hello Gustavo. He does not return anything. The return would be in xml. I just put the wrong user and password and gave Unauthorized. So he’s authenticating.

  • Could post the return of your xml?

  • Put a picture of him

Browser other questions tagged

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