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:

  1. We define an HTTPClient class with a sendGETRequest method.

  2. Inside sendGETRequest, we create a NSURL object with the target URL.

  3. We create an NSURLRequest object using the URL.

  4. We use [NSURLSession sharedSession] to get a shared URL session.

  5. We create an NSURLSessionDataTask with a completion handler. This handler is called when the request is complete.

  6. In the completion handler, we check for errors, print the response status, and print the first 5 lines of the response body.

  7. We start the task by calling [task resume].

  8. In the main function, we create an instance of HTTPClient and call the sendGETRequest method.

  9. 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:

  1. Save the code in a file named HTTPClient.m.
  2. Open a terminal and navigate to the directory containing the file.
  3. Compile the code using the Objective-C compiler:
$ clang -framework Foundation HTTPClient.m -o HTTPClient
  1. Run the compiled program:
$ ./HTTPClient

This 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.