ChatGPT解决这个技术问题 Extra ChatGPT

Adding Http Headers to HttpClient

I need to add http headers to the HttpClient before I send a request to a web service. How do I do that for an individual request (as opposed to on the HttpClient to all future requests)? I'm not sure if this is even possible.

var client = new HttpClient();
var task =
    client.GetAsync("http://www.someURI.com")
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

M
Massimiliano Kraus

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Thanks, Darrel! I was disappointed with HttpClient until I saw that you could do this.
Careful with this method. I have used it now to check if a bunch of urls were still available. A bunch of them returned 406 error purely because they did not have a "text/plain" mediaType to return.
@Talon That's what 406 means. The client asked for a media type that the server doesn't support. If you don't care what media type you get, then don't ask for one. The OP was simply asking how to add headers to a request. I just picked a random example.
These days you probably want var response = await client.SendAsync instead of ContinueWith and task.Wait()
Please note for best performance, you shouldn't instantiate an HTTP client like this. You can read more about this here stackoverflow.com/a/15708633/1406930
A
Aage

When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

I believe that that adds the header to all messages send by that HttpClient going forward. That contradicts the OP's point: "How do I do that for an individual request (as opposed to on the HttpClient to all future requests)?" HttpClient instances are designed to be created once and used many times.
To set custom headers on a request, build a request with the custom header before passing it to httpclient to send to http server. Default header is set on httpclient to send on every request to the server.
How can I later change this header? If I use another .Add("apikey","yyy"), it become "apikey: xxxxxxxxxyyy"
you can read headers and update?
This is the correct way to use it in modern .NET Core/6+ if your injecting the client using "services.AddHttpClient"
Z
Zimba

To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(someURL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
client.execute(request);

Default header is SET ON HTTPCLIENT to send on every request to the server.


The question is about the C# HttpClient, your code sounds like Java something
The question doesn't ask for C# solution. Question reads "I need to add http headers to the HttpClient before I send a request to a web service. How do I do that for an individual request (as opposed to on the HttpClient to all future requests)? I'm not sure if this is even possible." The solution I gave was to answer the question. If you are looking for code in some language, you may find code converters userful.
That's not true: the question is tagged C#, asp.net-web-api and dotnet-httpclient, so Java syntax is not relevant here, at all. Also, simple code converters in many cases won't fit language specific APIs: consider just the Java and C# HttpClient versions, they are deeply different and the conversion can result in a gross and not functioning code.