Brian F Love
Learn from a Google Developer Expert focused on Angular, Web Technologies, and Node.js from Portland, OR.
Ad ·
Learn Angular the right way with Ultimate Courses

Setting custom HTTP request headers with RestKit

RestKit is a great REST framework for Objective-C whose goal is to simplify consuming and modeling of RESTful APIs.

I am usingRestKitin an application that is synchronizing data between the client application and a remote server. I want to specify a custom HTTP header when sending the request to the remote server. With RestKit, it's actually really easy, but I wanted to document it here.

This assumes that you have already performed the initialization of the RestKit client, which is an instance of theRKObjectclass. In my project, I am using the object manager for mapping between the data payloads and Objective-C objects, so I will get access to the client instance through the shared object manager singleton. The first step is to get access to this client:

RKObjectManager*objectManager=[RKObjectManager sharedManager];RKClient*client=objectManager.client;

Then, it's as simple as calling the client'ssetValue:forHTTPHeaderField:method:

[client setValue:[NSString stringWithFormat:@"%d",[lastUpdated intValue]]forHTTPHeaderField:@"X-RESTKIT-LASTUPDATED"];

Here, I am using thelastUpdatedNSNumber,我在创建一个字符串teger value. This is a unix timestamp that I am going to send to my REST service for determining the last time the client was updated, so I can just send the records that have been updated since then. I am setting the value for the HTTP header called "X-RESTKIT-LASTUPDATED". Pretty easy, thanks to RestKit.

Setting HTTP Request header without using RestKit

RestKit does a nice job ofabstracting the details of using the nativeNSURLRequestandNSURLConnectionclasses. But, what if we were doing the request manually without using RestKit. Well, it's actually still fairly easy to set a custom HTTP request header. First, we will create a newNSURLRequest, which we will use for creating theNSURLConnection.

NSString*myServerUrl=@"";NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myServerUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];[request setValue:[NSString stringWithFormat:@"%d",[lastUpdated intValue]]forHTTPHeaderField:@"X-LASTUPDATED"];

We then use the request object to create theNSURLConnectionand fire off the request:

NSURLConnection*connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];

Brian F Love

Hi, I'm Brian. I am interested in TypeScript, Angular and Node.js. I'm married to my best friend Bonnie, I live in Portland and I ski (a lot).