有人帮我从gitlab网站获取JSON.我编写了我的代码但是当我编译代码时,我The remote server returned an error: (401) Unauthorized.
在控制台应用程序(C#)中收到了异常.
在我的浏览器中,当我在浏览器中登录时,我运行相同的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()); }
我的问题:
我犯了什么错误?
我知道我必须使用GET动词来获取API中的数据,但我不知道我必须在哪里使用GET动词?
提前致谢.
在您的请求中使用编码,凭证需要在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");