0

I'm writing a program that makes POST and GET calls asynchronously. The issue I'm running into is that each POST and GET sometimes have different headers/host parameters.

I have HttpClient initialized outside my main() class and inside my main class I have the following,

client.DefaultRequestHeaders.Add("Host", "website1.com");

and for another GET/POST request I want to have website2 in the HOST parameter,

client.DefaultRequestHeaders.Add("Host", "website2.com");

but they collide and it's throwing an error because it already exists. What's the proper way to approach this?

C O
  • 45
  • 10
  • 1
    Um, use two different client instances? – Jon Skeet Jul 25 '16 at 16:20
  • @jonskeet um, it's bad practice to make more then one instance of HttpClient. – C O Jul 25 '16 at 21:40
  • Never heard that before... And can't see why it would be. You want them configured differently, so create two of them. I'm not saying one per request - I'm saying one per configuration. Seems entirely reasonable to me. Do you have any documentation supporting your claim that this would be bad practice? – Jon Skeet Jul 25 '16 at 21:44
  • http://stackoverflow.com/questions/11178220/is-httpclient-safe-to-use-concurrently – C O Jul 25 '16 at 21:55
  • None of that says it's a bad idea to use multiple instances - it just says not to do it when you don't need to. In your case, you have a reasonable reason to create two, because they're configured differently. – Jon Skeet Jul 25 '16 at 21:57
  • http://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed/15708633#15708633 – C O Jul 25 '16 at 21:57
  • Same response as before. You're misunderstanding those answers IMO. – Jon Skeet Jul 25 '16 at 21:58

2 Answers2

0

Use SendAsync instead of GetAsync or PostAsync

var request = new HttpRequestMessage(HttpMethod.Get, new Uri("http://targeturi.com"));
request.Headers.Host = "website2.com"
var response = await client.SendAsync(request);

You can add as many headers as you want to the request before sending it

ndonohoe
  • 9,320
  • 2
  • 18
  • 25
  • For this method I would have to keep defining the headers for every single call right? Even for the same website? So website1.com has let's say 5 POST calls, and 2 GETs. I would have to declare the header in every method? – C O Jul 25 '16 at 16:38
  • Yes but you could easily create a simple wrapper method that you pass any required arguments and a host name into so you remove repeated code – ndonohoe Jul 26 '16 at 08:43
0

It is clear that you should use two separate instances of HttpClient, because DefaultRequestHeaders is not thread safely, and as result you will have problems with multi-threading cases.

See for more details : HttpClient–Is It Really Thread-Safe?

Klyuch
  • 66
  • 1
  • 6