Set Http Header for One Request

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

Angular - Set headers for every request

To answer, you question you could provide a service that wraps the original Http object from Angular. Something like described below.

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class HttpClient {

constructor(private http: Http) {}

createAuthorizationHeader(headers: Headers) {
headers.append('Authorization', 'Basic ' +
btoa('username:password'));
}

get(url) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(url, {
headers: headers
});
}

post(url, data) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.post(url, data, {
headers: headers
});
}
}

And instead of injecting the Http object you could inject this one (HttpClient).

import { HttpClient } from './http-client';

export class MyComponent {
// Notice we inject "our" HttpClient here, naming it Http so it's easier
constructor(http: HttpClient) {
this.http = httpClient;
}

handleSomething() {
this.http.post(url, data).subscribe(result => {
// console.log( result );
});
}
}

I also think that something could be done using multi providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

How to set headers in http get request?

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value")

How can i set Header map in case of custom HTTP Request in java?

The HttpRequestBuilder doesn't allow a direct set of the Map<String, List<String>> into the headers nor exposes an equivalent of putAll.

However, provided you have a Map<String, List<String>> called yourHeaders, then you can simply do the following:

HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(targetUrl)
.setHeader("Content-Type", "application/json")
.method(myMethod, HttpRequest.BodyPublishers.ofString(body));

yourHeaders.forEach((headerKey, headerValues) -> headerValues.forEach(value -> builder.header(headerKey, value)));

return builder.build();

How do you set the Content-Type header for an HttpClient request?

The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers):

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header

client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:

let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');

or

const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

Update: adding multiple headers

let headers = new HttpHeaders();
headers = headers.set('h1', 'v1').set('h2','v2');

or

const headers = new HttpHeaders({'h1':'v1','h2':'v2'});

Update: accept object map for HttpClient headers & params

Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders object an directly pass an object map as argument. So now its possible to do the following:

http.get('someurl',{
headers: {'header1':'value1','header2':'value2'}
});

How I add Headers to http.get or http.post in Typescript and angular 2?

You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get() and http.post() like this:

const headerDict = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
}

const requestOptions = {
headers: new Headers(headerDict),
};

return this.http.get(this.heroesUrl, requestOptions)

Or, if it's a POST request:

const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);

Since Angular 7 and up you have to use HttpHeaders class instead of Headers:

const requestOptions = {                                                                                                                                                                                 
headers: new HttpHeaders(headerDict),
};


Related Topics



Leave a reply



Submit