C#如何使用HttpWebRequest获取JSON字符串

时间:2017-01-12 07:39:56

标签: c# json httpwebrequest getjson gitlab-api

任何人帮我从gitlab网站获取JSON。我编写了代码,但是当我编译代码时,我在控制台应用程序(C#)中收到了异常The remote server returned an error: (401) Unauthorized.

在我的浏览器中,当我在浏览器中登录时,我运行相同的URL,我可以获取JSON字符串。如果我在从浏览器注销后运行相同的URL,我会在浏览器中收到{"message":"401 Unauthorized"}消息。

由于同样的例外情况,我认为我没有将用户名和凭据传递给我的HttpWebRequest

我在第HttpWebResponse response = request.GetResponse() as HttpWebResponse;

中获得了异常

我的代码:

            string URL = "http://gitlab.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());
            }

我的问题:

  1. 我犯了什么错误?
  2. 我知道我必须使用GET动词来获取API中的数据,但我不知道我在哪里使用GET动词?
  3. 提前致谢。

1 个答案:

答案 0 :(得分:6)

在您的请求中使用编码,凭据需要在ISO-8859-1中进行编码

        string URL = "http://gitlab.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.GetEncoding("ISO-8859-1").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());
        }

如果不起作用,请删除标题行并将其替换为以下内容:

request.Credentials = new NetworkCredential("username", "password");