How to use Infatica Residential proxy with C#
Using WebRequest
using System;
using System.IO;
using System.Net;
namespace ProxyRequest
{
class MainClass
{
public static void Main(string[] args)
{ # Change the proxy login, password, IP, and port from your proxy list if you use authorization by login/password.
var myProxy = new WebProxy("http://Host:Port", true);
myProxy.Credentials = new NetworkCredential("login", "password");
var request = (HttpWebRequest)WebRequest.Create("http://ip-api.com");
request.Proxy = myProxy;
request.PreAuthenticate = true;
request.AllowAutoRedirect = false;
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
var response = request.GetResponse();
Console.WriteLine("Response Status: " + ((HttpWebResponse)response).StatusDescription);
Console.WriteLine("\nResponse Headers:\n" + ((HttpWebResponse)response).Headers);
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine("Response Body:\n" + responseFromServer);
reader.Close();
response.Close();
}
}
}
Asynchronous Request with HttpClient
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AsyncProxyRequest
{
class MainClass
{
static void Main(string[] args)
{
_ = AsyncMain();
Console.ReadKey();
}
public static async Task AsyncMain()
{
string requestUri = "http://ip-api.com";
string crawleraApiKey = "login:password";
string crawleraAuth = Convert.ToBase64String(
Encoding.Default.GetBytes(crawleraApiKey ));
string crawleraUri = string.Format(
"{0}:{1}", "IP", "port");
WebProxy proxy = new WebProxy(crawleraUri, true);
CookieContainer cookieContainer = new CookieContainer();
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
PreAuthenticate = false,
UseDefaultCredentials = false,
UseProxy = true,
UseCookies = true,
CookieContainer = cookieContainer
};
HttpClient client = new HttpClient(httpClientHandler);
int _TimeoutSec = 300;
client.Timeout = new TimeSpan(0, 0, _TimeoutSec);
client.DefaultRequestHeaders.Add("Proxy-Authorization", "Basic " + crawleraAuth);
try
{
HttpResponseMessage response = await client.GetAsync(requestUri);
HttpContent content = response.Content;
Console.WriteLine("Response Status Code: " + (int)response.StatusCode);
string scrapedPage = await content.ReadAsStringAsync();
Console.WriteLine("Response Content: " + scrapedPage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}