我正在编写简单的代码,该代码在向它发送 POST 请求后从 http 服务器向我发送响应,但是如果我尝试将所有内容移动到另一个文件,XCode 会向我显示此错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“数据参数为零”
这是我用来完成这项工作的两个文件:
#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