user6874415
user6874415

Reputation:

Get the JSON by using API in c# console application

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.

Upvotes: 1

Views: 3059

Answers (2)

Muhammad Usama Alam
Muhammad Usama Alam

Reputation: 209

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";
        }
 }

Upvotes: 1

Andrei Filimon
Andrei Filimon

Reputation: 1188

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.

Upvotes: 0

Related Questions