How to use proxy in Http client

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:

I recently subscribed a paid proxy service, it works well. Since I am using a fixed IP address, the proxy service can authenticate me via my IP address, so I don't have to input user name, password to get through.

However, I can't find any good C# code sample on how to create a httpclient using proxy without user name/password.

All the examples I saw needs user name/password.

I have the following C# code:

public static async Task<string> Http1_Get_With_Proxy(string url1)
{
string html_content = "";
try
{
WebProxy proxy = new WebProxy
{
Address = new Uri($"1.2.3.4:8888"),
};
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpClientHandler clientHandler = new HttpClientHandler()
{
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
Proxy = proxy,
};
using HttpClient client1 = new HttpClient(clientHandler);
client1.DefaultRequestHeaders.Accept.Clear();
client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
client1.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url1);
HttpResponseMessage response = await client1.SendAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
{
html_content = await response.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException ex)
{
Console.WriteLine(ex.Message);
}
return (html_content);
}


When I ran my code, I got error message:

{"Invalid URI: The URI scheme is not valid."}

I can understand the error, since pure IP address is not a valid URI, but how I can do this? I just want to use pure IP:Port# without http://, as I don't need them for the proxy service.

I even want one step further: how I can do this for HTTP2 client?

By the way, I am using Visual Studio 2019 Version 16.3.3 on Windows 10 (1903).

Please advice!

Continue reading...
 
Back
Top