Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLRequest setting the HTTP header

I need to set the HTTP header for a request. In the documentation for the NSURLRequest class I didn't find anything regarding the HTTP header. How can I set the HTTP header to contain custom data?

like image 984
Raphael Avatar asked Jan 26 '11 19:01

Raphael


People also ask

How do I add a header to my HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers. For example: oRequest = RequestBuilder:Build('GET', oURI) :AddHeader('MyCustomHeaderName','MyCustomHeaderValue') :AddHeader('MySecondHeader','MySecondHeaderValue') :Request.

What is in a HTTP header?

An HTTP response header includes information in a text-record form that a Web server transmits back to the client's browser. The response header contains particulars such as the type, date and size of the file sent back by the server, as well as information regarding the server.

What is NSURLConnection?

An NSURLConnection object lets you load the contents of a URL by providing a URL request object. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request. You perform most of your configuration on the URL request object itself.


2 Answers

You need to use a NSMutableURLRequest

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]                                 autorelease];  [request setValue:VALUE forHTTPHeaderField:@"Field You Want To Set"]; 

or to add a header:

[request addValue:VALUE forHTTPHeaderField:@"Field You Want To Set"]; 
like image 55
Larry Hipp Avatar answered Sep 28 '22 06:09

Larry Hipp


for Swift

let url: NSURL = NSURL(string: APIBaseURL + "&login=1951&pass=1234")! var params = ["login":"1951", "pass":"1234"] request = NSMutableURLRequest(URL:url) request.HTTPMethod = "POST" var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") 
like image 26
Beslan Tularov Avatar answered Sep 28 '22 05:09

Beslan Tularov