1

I have a C# application which needs to call a WooCommerce API and read its HTML response. I use this code:

public static String code(string Url)
{

    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
    myRequest.Method = "GET";

    WebResponse myResponse = myRequest.GetResponse();

    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
    string result = sr.ReadToEnd();
    sr.Close();
    myResponse.Close();

    return result;
}

but I get this error on the selected line:

The remote server returned an error: (401) Unauthorized.

I tried several ways but like every time I got the same error; these are some ways I tried to solve it:

myRequest .UseDefaultCredentials = true;
myRequest .PreAuthenticate = true;
myRequest .Credentials = CredentialCache.DefaultCredentials;

or

request.Credentials = new NetworkCredential("UserName", "PassWord");
request.UseDefaultCredentials = true; request.PreAuthenticate = true;

In addition, I should say that when I open my URL in the browser for the first time, Chrome shows me a security alert, but just for the first time. Please help me, I really need to solve this.

Francesco B.
  • 2,729
  • 4
  • 25
  • 37
omid alaie
  • 25
  • 6

1 Answers1

0

That's because you are connecting to an HTTPS service with an invalid certificate (which you should ignore, since apparently you trust that service).

Here on StackOverflow there's a similar question, whose accepted answer I am including into your code:

public static String code(string Url)
{
    ServicePointManager.ServerCertificateValidationCallback = 
        new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
    myRequest.Method = "GET";

     WebResponse myResponse = myRequest.GetResponse();

    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
    string result = sr.ReadToEnd();
    sr.Close();
    myResponse.Close();

    return result;
}

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}
Francesco B.
  • 2,729
  • 4
  • 25
  • 37