Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple C# .NET 4.5 HTTPClient Request Using Basic Auth and Proxy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net;
namespace HTTP_Test
{
class program
{
static void Main()
{
Task t = new Task(HTTP_GET);
t.Start();
Console.ReadLine();
}
static async void HTTP_GET()
{
var TARGETURL = "http://en.wikipedia.org/";
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true,
};
Console.WriteLine("GET: + " + TARGETURL);
// ... Use HttpClient.
HttpClient client = new HttpClient(handler);
var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = await client.GetAsync(TARGETURL);
HttpContent content = response.Content;
// ... Check Status Code
Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
Console.WriteLine(result.Substring(0, 50) + "...");
}
}
}
}
@ghost

This comment has been minimized.

Copy link

commented Dec 5, 2015

Thanks for the code!

@fusion27

This comment has been minimized.

Copy link

commented Dec 15, 2015

👍 Thank you for the code, you saved me time. Take the rest of the day off!

@Gongmoune

This comment has been minimized.

Copy link

commented Feb 28, 2016

hi, i am new in programmation. i want to connect a HTTP-server with an webbrowser. so the browser shall send an xml-code to the server. then the server modify it and send back to the browser. i have no idea. can everyone help me pleace?

@acrolink

This comment has been minimized.

Copy link

commented Apr 30, 2016

Thank you very much

@Cosmos-it

This comment has been minimized.

Copy link

commented Aug 22, 2016

Oh yeah. Thanks.
That is what I am looking for. Did it in python but my company is big on .NET platform. So I am about to switch that.

@nik-pakhomov

This comment has been minimized.

Copy link

commented Aug 24, 2016

Thanks!

@stpriyanka

This comment has been minimized.

Copy link

commented Sep 19, 2016

thanks . saved a lot of times

@dteemull

This comment has been minimized.

Copy link

commented Nov 22, 2016

Why not use the .Net built-in BasicAuthenticationHeaderValue (also in the System.Net.Http.Headers namespace)? Like this:
client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(username, password);

  • where username and password are vars for the actual credentials
@epicstar

This comment has been minimized.

Copy link

commented Jan 3, 2017

@dteemull, I can't reference BasicAuthenticationHeaderValue for some reason in my project that uses .net 4.5

@SandeepApsingekar

This comment has been minimized.

Copy link

commented Jan 27, 2017

Hi bryanbarnard.

I'm working on making something similar to this. I'm trying to write a class which uses httpclient to invoke an endpoint and gets the response. I would really appreciate if you can explain me what does your logic do. So that I can work on mine taking your code as reference.

Thank You!

@leandrohumberto

This comment has been minimized.

Copy link

commented Mar 16, 2017

Helped me a lot. Thanks!

@robsmith1776

This comment has been minimized.

Copy link

commented Apr 26, 2017

Thanks

@cyrusjohan

This comment has been minimized.

Copy link

commented May 14, 2017

Gracias por ese pedazo de codigo me salvo la tarde!!!

@gfoidl

This comment has been minimized.

Copy link

commented Jun 16, 2017

Thanks! This solution works also on raspberry pi 3 with .net Core 2.0 (preview).

This works on Windows, Linux (Ubuntu 16.04-x64) with .net Core 1.1 and 2.0 (preview):

var credentials = new NetworkCredential(user, password);
var handler     = new HttpClientHandler { Credentials = credentials };
var http        = new HttpClient(handler);

On raspberry pi 3 this throws A task was canceled.

The solution in this gist runs "everywhere" 👍

@bitbonk

This comment has been minimized.

Copy link

commented Jun 20, 2017

Regarding this line:

Encoding.ASCII.GetBytes("username:password1234");

If I read the standard correctly it is not a requirment that need to be ASCII. So it would be (more) correct to use Encoding.Unicode.GetBytes($"{userName}:{password}");

Do you agree?

@xujiesh0510

This comment has been minimized.

Copy link

commented Jun 26, 2017

Many thanks .Buddy!

@mausworks

This comment has been minimized.

Copy link

commented Jul 3, 2017

@bitbonk That depends on what encoding the server expects. But as long as only ASCII-characters are used in the username/password it will have the same result as Unicode uses the same byte values for all ASCII-characters, good call Unicode consortium.

I created a rudimentary helper-class for basic authentication which takes encoding into account for all stringbyte[] operations.

@htn5723

This comment has been minimized.

Copy link

commented Sep 20, 2017

hello ders
it is good
i want to send and receive async with keep a live
help me plz?

@slobadx

This comment has been minimized.

Copy link

commented Feb 20, 2018

Many thanks dude!

@kiquenet

This comment has been minimized.

Copy link

commented Feb 22, 2018

Good! Any OAuth1 and OAuth2 extension ?

@kiquenet

This comment has been minimized.

Copy link

commented Feb 22, 2018

There is a debate whether HttpClient should be wrapped in using block or statically on the app level. Although it implements IDisposable, it seems that by wrapping it in the using block, you can make your app malfunction and get the SocketException. And as Ankit blogs, the performance test results are much in favor of static initialization of the HttpClient. Be sure to read these blog posts as they can help you be more informed about the correct usage of the HttpClient.
And don’t forget, being modern, HttpClient is exclusive to the .NET 4.5, so you might have trouble using it on some legacy projects.

Wrong usage of the HTTPClient class (in .NET)

In .NET, as Simon Timms described in his article, you have to be careful when using the HTTPClient class.
Continuous instantiation and disposal of the HTTPClient object may create a socket exhaustion on your machine and affect performance.
Consider reusing the HTTPClient object throughout your calls for better performance.

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
https://ankitvijay.net/2016/09/25/dispose-httpclient-or-have-a-static-instance/

@syedimraa

This comment has been minimized.

Copy link

commented Apr 5, 2018

Hi , I want to call the third party SMS APi call - TransmitSMS from my .net web application that uses framework 4.5. during the call i want to send authorisation , parameter everything. i am new to the programming. can any guys help on this.

I already tried using http client:

i always get the following error :

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: close
Date: Wed, 04 Apr 2018 12:06:52 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 334
Content-Type: text/html; charset=us-ascii
}}

following is the code i wrote for calling
public string CancelParameters = "message=12&to=6512312312";
public string URL = "http://api.transmitsms.com/send-sms.json";
try
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://localhost:53436"),
UseProxy = true,

            };

            HttpClient client = new HttpClient(handler);
            client.BaseAddress = new Uri(URL);
            //WebProxy.GetDefaultProxy();

           
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "myusername(apikey)", "my password(secret)"))));
            HttpResponseMessage response = client.GetAsync(CancelParameters).Result;
        }
        catch (Exception ex)
        {
            ex.InnerException.ToString();
        }

can anybody please help on this. thanks in advance.

@jdalvarez18

This comment has been minimized.

Copy link

commented Feb 15, 2019

Muchas gracias

@enikitin

This comment has been minimized.

Copy link

commented Mar 15, 2019

Very nice! I was able to intercept HttpClient with Fiddler on port 58888!

@jindeveloper

This comment has been minimized.

Copy link

commented Jun 9, 2019

thanks, men.

@CristiCor

This comment has been minimized.

Copy link

commented Jun 25, 2019

God bless you !!
I lost a day yesterday to get done some GET to external API..
Thank you !! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.