我正在尝试从Rest API获取数据。API需要3个东西来提供身份验证;
第一个是"接受:应用程序/vnd.###.v1.0 + json"
第二个:"内容类型:应用程序/json "
第三个:Base64编码的"用户名:密码"字符串
我应该通过这些凭证的验证和授权自定义头。我知道有很多线程在这个网站上关于这个主题,但我不能解决他们的问题。
下面是代码块:
public class McAfeeIPSManager
{
String URL = "https://serviceOfApi/sdkapi/session";
public void getWebRequest()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
String username = "user";
String password = "password1";
var request = HttpWebRequest.Create(URL) as HttpWebRequest;
request.Accept = "application/vnd.###.v2.0+json";
request.Method = "GET";
request.ContentType = "application/json";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization","Basic "+encoded);
try
{
// Get response
using (var response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
using (var responseReader = new StreamReader(response.GetResponseStream()))
{
string responseBody = responseReader.ReadToEnd();
// Console application output
System.Diagnostics.Debug.Write("Response Body ---> " + responseBody);
//Console.WriteLine(responseBody);
}
}
}
catch (WebException ex)
{
System.Diagnostics.Debug.Write("Error : " + ex.Message);
Console.WriteLine("Error: {0}", ex.Message);
}
}
}
在这种情况下如何从WebAPI获取数据?有人能帮我吗?
2条答案
按热度按时间jq6vz3qz1#
您没有预身份验证和凭据?我有一个代码可以帮助您:
ubof19bj2#
嗯,除了我发布的东西,尝试处理这个,它应该对你有用,希望: