简体   繁体   中英

The remote server returned an error: (401) Unauthorized when requesting RestApi data

I am triyng to get data from the Rest API. API wants 3 things to give authentication;

first one is "Accept:application/vnd.###.v1.0+json"

second one : "Content Type : application/json"

third one : Base64 encoded "userName:password" string

and I should pass these credentials for validation and authorization in custom header.I know there are a lot of thread on this site about this topic but I couldn't solve the problem from them.

Here is the code block :

 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);
        }

    }
}

How can get data from WebAPI under these conditions?Can anybody help me?

You have no PreAuthenticate and credential ? I have a code that may help you:

  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();

hmm in addition of what i post try deal with this it should work for you hope:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM