Question

This code is written with python:

import urllib3
http = urllib3.PoolManager()
url = "http://www.example.com/"
req = http.request('GET', url)
source = req.dat

I want to know how can I write it with C#.

Was it helpful?

Solution 2

If you want just to download from URL you can try using

  String url = @"http://www.example.com/";
  Byte[] dat = null;

  // In case you need credentials for Proxy
  if (Object.ReferenceEquals(null, WebRequest.DefaultWebProxy.Credentials))
    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;

  using (WebClient wc = new WebClient()) {
    // Seems that you need raw data, Byte[]; if you want String - wc.DownLoadString(url);
    dat = wc.DownloadData(url);
  }

OTHER TIPS

Use following code:

using (WebClient client = new WebClient ()) // Use using, for automatic dispose of client
{
    //Get HTMLcode from page
    string htmlCode = client.DownloadString("http://www.example.com");
}

Add reference to System.Net at top of your class:

using System.Net;

But Oliver's answer offers more control :).

It looks like you're downloading a web response. Below is one way to do this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/");

using (var stream = request.GetResponse().GetResponseStream())
{
   var reader = new StreamReader(stream, Encoding.UTF8);
   var responseString = reader.ReadToEnd();
}

But Max's answer is easier :).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top