asp.net 远程服务器返回错误:(401)请求RestApi数据时未经授权

wgx48brx  于 2023-02-20  发布在  .NET
关注(0)|答案(2)|浏览(219)

我正在尝试从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获取数据?有人能帮我吗?

jq6vz3qz

jq6vz3qz1#

您没有预身份验证和凭据?我有一个代码可以帮助您:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://pwmaffr2:8443/remote/system.delete?names=" + DeviceName + "");
                    request.Headers.Add("AUTHORIZATION", "Basic YTph");
                    request.ContentType = "text/html";

                    request.Credentials = new NetworkCredential(Username, Password);
                    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                    request.PreAuthenticate = true;
                    request.Method = "GET";
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    );

                    StreamReader stream = new StreamReader(response.GetResponseStream());
                    string X = stream.ReadToEnd();
ubof19bj

ubof19bj2#

嗯,除了我发布的东西,尝试处理这个,它应该对你有用,希望:

string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("basic ", base64);
request.Headers.Add("Authorization", authorization);

相关问题