向HTTP发送POST请求时出现NSInvalidArgumentException

时间:2013-05-16 23:07:11

标签: ios http httprequest

我正在编写简单的代码,它在发送POST请求后从http服务器向我发送响应但是如果我尝试将所有内容移动到另一个文件,XCode会向我显示此错误:

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'data parameter is nil'

以下是我用来完成这项工作的两个文件:

   #import "HTTPRequestHandler.h"

@interface HTTPRequestHandler ()

@property (strong, nonatomic) NSURL *requestURL;
@property (strong, nonatomic) NSData *httpBody;
@property (strong, nonatomic) NSMutableData *responseData;

@end

@implementation HTTPRequestHandler

- (id)initWithURL:(NSString *)url body:(NSString *)body
{
    if (self = [super init]) {
        self.requestURL = [[NSURL alloc] initWithString:url];
        self.httpBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    }

    return self;
}

- (void)makeConnectionWithRequest
{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:self.requestURL];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:self.httpBody];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Dane doszły 1");
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Dane doszły 2");
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Dane doszły 3");


   NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
    NSLog(@"%@", [recievedData description]);
}

@end

和第二个:

#import "ViewController.h"
#import "HTTPRequestHandler.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    HTTPRequestHandler *request = [[HTTPRequestHandler alloc] initWithURL:@"http://own-dev1.railwaymen.org:4006/api/get_grant_key"
                                                                     body:@"email=vergun@gmail.com&password=password"];
    [request makeConnectionWithRequest];
}

@end

1 个答案:

答案 0 :(得分:0)

哎呀,明白了!刚忘了self.responseData = [NSMutableData data];