Skip to content

Instantly share code, notes, and snippets.

@bryanbarnard
Created December 23, 2013 19:15
Show Gist options
  • Save bryanbarnard/8102915 to your computer and use it in GitHub Desktop.
Save bryanbarnard/8102915 to your computer and use it in GitHub Desktop.
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) + "...");
}
}
}
}
@kiquenet
Copy link

Good! Any OAuth1 and OAuth2 extension ?

@kiquenet
Copy link

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
Copy link

syedimraa 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
Copy link

Muchas gracias

@enikitin
Copy link

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

@jindeveloper
Copy link

thanks, men.

@CristiCor
Copy link

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

@quarinteen
Copy link

Not sure what gives but for what ever reason creating the task and running it in main with t.start() does nothing. I don't get any errors it just stops when it hits the closing {} of Main(string[] args). The only thing different I added was user input on user name and password and I added an encryption method .

So I have the Main(string[] args then I have the following

` public async Task EncodePass(string password)
{

        byte[] bytes = Encoding.Unicode.GetBytes(password);
        byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
        return Convert.ToBase64String(inArray);
    }`

Then I have
`static async void HTTP_GET()
{

}`

@Mskirvk
Copy link

Mskirvk commented Jan 29, 2020

THANK YOU MAN!

@dogac00
Copy link

dogac00 commented Dec 16, 2020

Thank you very much.

@JustinaMary
Copy link

Thank you very much, you saved my day

@BerkAngay-terminal
Copy link

thankkk youuuu

@thomasroodnl
Copy link

It took me a while to find out how to encode the username and password into the authorization header, your code saved me a lot of trouble, thanks!

@kvadrakot
Copy link

thanks!

@wicky05
Copy link

wicky05 commented Mar 16, 2022

Great Work?

Can you guide me

How to handle below json format using C# (with Authentication) - Post Method with Body(Raw)

{

"CustomerCode": "F101",
"CusReferenceNo": "3",
"StationName": "fsa",
"SalesmanId": "5",
"OrderStatus": "CLS",
"PostingDate": "2021-01-07",

"orderDetails":[
    {

"ItemCode": "100-0001-00002",
"Quantity": "25000.000000",

}]

}

Appreciated, if you guide me and share sample code

@gnraju20411
Copy link

gnraju20411 commented Jul 21, 2022

Getting trouble with downloading the PFD files from the webpage ("https://www.*******.com/produ/abc.pdf) with user authentication through using C# "HttpClient"
The webpage having some Cookies also
i followed the same as your code.

Please guide me how download through code (C#)?

@RamadanEssam
Copy link

Getting trouble with downloading the PFD files from the webpage ("https://www.*******.com/produ/abc.pdf) with user authentication through using C# "HttpClient"
The webpage having some Cookies also
i followed the same as your code.

@chardalas
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment