Http Client in Objective-C
Here’s an idiomatic Objective-C example demonstrating how to create a simple HTTP client:
#import <Foundation/Foundation.h>
@interface HTTPClient : NSObject
- (void)sendGETRequest;
@end
@implementation HTTPClient
- (void)sendGETRequest {
// Create a URL object
NSURL *url = [NSURL URLWithString:@"https://api.example.com"];
// Create a URL request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Create a URL session
NSURLSession *session = [NSURLSession sharedSession];
// Create a data task
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
return;
}
// Cast the response to NSHTTPURLResponse
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
// Print the response status
NSLog(@"Response status: %ld", (long)httpResponse.statusCode);
// Print the first 5 lines of the response body
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSArray *lines = [responseString componentsSeparatedByString:@"\n"];
for (NSUInteger i = 0; i < MIN(5, lines.count); i++) {
NSLog(@"%@", lines[i]);
}
}];
// Start the task
[task resume];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
HTTPClient *client = [[HTTPClient alloc] init];
[client sendGETRequest];
// Keep the main thread running to allow the asynchronous task to complete
[[NSRunLoop currentRunLoop] run];
}
return 0;
}This Objective-C example demonstrates how to create a simple HTTP client using the NSURLSession API. Here’s a breakdown of the code:
We define an
HTTPClientclass with asendGETRequestmethod.Inside
sendGETRequest, we create aNSURLobject with the target URL.We create an
NSURLRequestobject using the URL.We use
[NSURLSession sharedSession]to get a shared URL session.We create an
NSURLSessionDataTaskwith a completion handler. This handler is called when the request is complete.In the completion handler, we check for errors, print the response status, and print the first 5 lines of the response body.
We start the task by calling
[task resume].In the
mainfunction, we create an instance ofHTTPClientand call thesendGETRequestmethod.We use
[[NSRunLoop currentRunLoop] run]to keep the main thread running, allowing the asynchronous task to complete.
To compile and run this Objective-C program:
- Save the code in a file named
HTTPClient.m. - Open a terminal and navigate to the directory containing the file.
- Compile the code using the Objective-C compiler:
$ clang -framework Foundation HTTPClient.m -o HTTPClient- Run the compiled program:
$ ./HTTPClientThis example demonstrates how to make HTTP requests in Objective-C using the NSURLSession API, which is the modern and recommended way to perform network operations in Objective-C and iOS development. It showcases error handling, response parsing, and asynchronous programming patterns common in Objective-C.