通过在c#console应用程序中使用API​​来获取JSON

时间:2017-01-10 12:01:36

标签: c# json httpwebrequest

我尝试使用API​​获取JSON字符串。我试过HttpWebResponseWebRequest。但是这两种方法都得到了异常The remote server returned an error: (401) Unauthorized.这个异常可能是用户名和密码。但我使用正确的凭证。我不知道我在哪里犯了错误。

我的代码是:

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());
}

我犯了哪个错误?

提前致谢。

2 个答案:

答案 0 :(得分:0)

此代码可以演示如何调用 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;
}

新功能休息Api

必须为JavaScriptSerializer导入DLL System.Web System.Web.Extensions

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

答案 1 :(得分:0)

你这里做错了什么:

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

您在上面设置的值不是API预期的值。