Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get https files based on URL in asp.net c#

Tags:

c#

.net

asp.net

In my requirement, I need to get the file from a URL. I tried, but it always throws a forbidden error. Please try to solve this problem. Please look in to my code.

var webRequest = WebRequest.Create("https://www.fda.gov/ucm/groups/fdagov-public/@fdagov-drugs-gen/documents/document/ucm509432.pdf");  
using (var response = webRequest.GetResponse())
   using (var content = response.GetResponseStream())
      using (var reader = new StreamReader(content))
      {
         var strContent = reader.ReadToEnd();
      }
like image 326
chaitanya Avatar asked Feb 09 '26 19:02

chaitanya


1 Answers

When I checked the response contents from the server, I realized that it is stating that the client needed to Support TLSv1.2.

To enable TLSv1.2 support, add the following line before creating the HttpWebRequest class: (Thanks BugFinder for the direct enumeration value tip)

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

I am posting the complete source code.

You can also see that I tested sending some headers to the server to see if the absence of one of them was the problem:

class Program
{
    static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        HttpWebRequest webRequest = HttpWebRequest.Create("https://www.fda.gov/ucm/groups/fdagov-public/@fdagov-drugs-gen/documents/document/ucm509432.pdf") as HttpWebRequest;
        webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko";
        webRequest.Accept = "text/html, application/xhtml+xml, */*";
        webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
        webRequest.Headers.Add("Accept-Language", "tr-TR");
        webRequest.Headers.Add("DNT", "1");

        using (var
             response = webRequest.GetResponse())
        using (var content = response.GetResponseStream())
        using (var reader = new StreamReader(content))
        {
            var strContent = reader.ReadToEnd();
        }
    }
}
like image 161
Oguz Ozgul Avatar answered Feb 12 '26 16:02

Oguz Ozgul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!