我是新来的api's并通过.NET调用它们
我有一个api:https://sub.domain.com/api/operations?param=value¶m2=value
api的注释说要授权我需要使用基本的访问身份验证 - 我该怎么做?
我目前有这段代码:
WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value¶m2=value");
req.Method = "GET";
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
但是我收到了401未经授权的错误。
我缺少什么,如何使用基本访问身份验证形成api呼叫?
答案 0 :(得分:49)
如果API说要使用HTTP基本身份验证,则需要在请求中添加Authorization标头。我会改变你的代码看起来像这样:
WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value¶m2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
当然,用正确的值替换"username"
和"password"
。
答案 1 :(得分:0)
您还可以使用RestSharp库 例如
var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
答案 2 :(得分:0)
这是Rest API的解决方案
htmlentitydefs