0
我写简单的代码是给我从HTTP服务器响应发送POST请求之后,但如果我尝试一切移动到另一个文件的XCode表明我这个错误:NSInvalidArgumentException在发送POST请求HTTP
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '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 protected]&password=password"];
[request makeConnectionWithRequest];
}
@end