1

I tried to take the JSON string by using the API. I tried by HttpWebResponse and WebRequest. But Both method I got the exception The remote server returned an error: (401) Unauthorized. This exception might be the username and password. But I using correct credential.I don`t know where I did the mistake.

My code is:

string URL = @"http://abc.company.com/api/v3/users?per_page=100&page=1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json; charset=utf-8";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("userName:passWord"));
request.PreAuthenticate = true;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
    Console.WriteLine(reader.ReadToEnd());
}

Where I did the mistake?

Thanks in advance.

3
  • 2
    Have you tried setting the Credentials property of the request, rather than trying to do it yourself? Commented Jan 10, 2017 at 12:03
  • @Moo-Juice Sorry, I have not tried. also, I don`t have the awareness about it. I am new to REST API Commented Jan 10, 2017 at 12:07
  • Are you sure that the logic you use to generate the Authorization header value is the proper one? (you must get it from the REST API provider) Commented Jan 10, 2017 at 12:34

2 Answers 2

1

This Code Can Demonstrate How to call REST Api

public static string CallRestMethod(string url)
{
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
    webrequest.Method = "GET";
    webrequest.ContentType = "application/x-www-form-urlencoded";
    webrequest.Headers.Add("Username", "xyz");
    webrequest.Headers.Add("Password", "abc");
    HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
    Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
    StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
    string result = string.Empty;
    result = responseStream.ReadToEnd();
    webresponse.Close();
    return result;
}

New Function Rest Api

Must Import Dll System.Web and System.Web.Extensions for JavaScriptSerializer

using System.Web.Script.Serialization;

public string Requst(string Url, string Method, object Parameter)
{
        try
        {
            var result = "";
            var url = Url;
            var webrequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
            webrequest.ContentType = "application/json";
            webrequest.Method = Method.ToString();

            NetworkCredential netcred = new NetworkCredential(){
                Domain = "",
                UserName = "",
                Password = ""
            };

            webrequest.Credentials = netcred;

            if (Method.ToString() == "POST")
            {
                using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
                {
                    streamWriter.Write(new JavaScriptSerializer().Serialize(Parameter));
                }
            }

            var httpResponse = (HttpWebResponse)webrequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }

            return result.ToString();
        }
        catch (Exception ex)
        {
            return "-1";
        }
 }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your responses. I have altered my code as per your example but now also I face same 401 exception.
@Muhamadd Usama Alam Thank you for your response. Again I face the same 401 exception :(
@Arunald if you have 3rd party web api so give me the link of this api provider so i will test it and provide the solution of your problem
kindly check your api private key or create a new api private key Link
0

You are doing something wrong here:

 request.Headers["Authorization"]=
Basic+
Convert.ToBase64String(Encoding.Default.GetBytes("userName:passWord"));

The value you set above is not the one expected by the API.

2 Comments

Yeah! You are right. Due to this line fault, I get the 401 unauthorized error. But I don`t know what is that!
You must get the info of how to generate the value from the REST API provider, because it is an API specific, can be done in many ways.