2014年8月16日土曜日

NSURLSessionを使ってHTTPリクエストする

NSURLSessionDataTaskを使って、HTTP-GET、JSONデータをHTTP-POSTする。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *requestUrl;
@property (weak, nonatomic) IBOutlet UITextField *requestBody;
@property (weak, nonatomic) IBOutlet UITextView *requestResult;
- (IBAction)getAsync:(id)sender;
- (IBAction)postAsync:(id)sender;

@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// HTTP-GET
- (IBAction)getAsync:(id)sender {
    NSLog(@"%s", __func__);
    
    // create the url-request
    NSURL *url = [NSURL URLWithString:self.requestUrl.text];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // set the method(HTTP-GET)
    [request setHTTPMethod:@"GET"];
    
    // use NSURLSessionDataTask
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (!error) {
            NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;
            NSLog(@"statusCode: %ld", (long)httpRes.statusCode);
            NSLog(@"allHeaderFields: %@", httpRes.allHeaderFields);
            
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"result: %@", result);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.requestResult.text = result;
            });
            
        } else {
            NSLog(@"error: %@", [error localizedDescription]);
        }
        
    }];
    
    [task resume];
}

// HTTP-POST
- (IBAction)postAsync:(id)sender {
    NSLog(@"%s", __func__);
    
    // create the url-request
    NSURL *url = [NSURL URLWithString:self.requestUrl.text];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // set the headers(s)
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // set the method(HTTP-POST)
    [request setHTTPMethod:@"POST"];

    // set the request-body
    NSString *reqBody = self.requestBody.text;
    NSLog(@"%@", reqBody);

    [request setHTTPBody:[reqBody dataUsingEncoding:NSUTF8StringEncoding]];
    
    // use NSURLSessionDataTask
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (!error) {
            NSHTTPURLResponse *httpRes = (NSHTTPURLResponse *)response;
            NSLog(@"statusCode: %ld", (long)httpRes.statusCode);
            NSLog(@"allHeaderFields: %@", httpRes.allHeaderFields);
            
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"result: %@", result);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.requestResult.text = result;
            });
            
        } else {
            NSLog(@"error: %@", [error localizedDescription]);
        }
        
    }];
    
    [task resume];
}

@end

0 件のコメント:

コメントを投稿