【问题标题】:NSInvalidArgumentException in sending POST request to HTTP向 HTTP 发送 POST 请求时出现 NSInvalidArgumentException
【发布时间】:2013-05-16 23:07:10
【问题描述】:

我正在编写简单的代码,该代码在向它发送 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

【问题讨论】:

    标签: ios http httprequest


    【解决方案1】:

    好的,明白了!忘了self.responseData = [NSMutableData data];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多