Writing an iOS http Post class



我正在尝试编写一个可用于发出HTTP Post请求并检索请求结果的类。有些东西没有完全连接,因为我没有得到任何确认,甚至没有失败消息。我的前两个 NSLog 生成了,但连接方法没有任何返回。什么都不会崩溃,它只是不回来。这是我得到的唯一输出:

&first=vic&second=tory
www.mySite.com/phpTest.php

能够成功地发出简单的HTTP请求,所以我知道我的问题与连接等无关。此外,目前,这个 php 脚本忽略了我发送给它的参数,以便我可以在测试/调试时尽可能保持简单。应该发生的只是应该返回"成功"一词。

谁能看到出了什么问题?谢谢!

这是我的调用方法:

- (IBAction)phpTest:(UIBarButtonItem *)sender
{
    //set post string with actual parameters
    NSString *post = [NSString stringWithFormat:@"&first=%@&second=%@", @"vic", @"tory"];
    NSString *script = @"phpTest.php";
    NSLog(@"%@", post);
    MyDownloader *d = [[MyDownloader alloc] initWithPost:post script:script];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(finished:)
                                                 name:@"connectionFinished"
                                               object:d];
    [d.connection start];
}
- (void) finished: (NSNotification *) n
{
    MyDownloader *d = [n object];
    NSData *data = nil;
    if ([n userInfo]) {
        NSLog(@"information retrieval failed");
    } else {
        data = d.receivedData;
        NSString *text=[[NSString alloc]initWithData:d.receivedData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", text);
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"connectionFinished"
                                                  object:d];
}

我的下载器.m

@interface MyDownloader()
@property (nonatomic, strong, readwrite) NSURLConnection *connection;
@property (nonatomic, copy, readwrite) NSMutableURLRequest *request;
@property (nonatomic, copy, readwrite) NSString *postString;
@property (nonatomic, copy, readwrite) NSString *script;
@property (nonatomic, strong, readwrite) NSMutableData *mutableReceivedData;
@end
@implementation MyDownloader
- (NSData *) receivedData
{
    return [self.mutableReceivedData copy];
}
- (id) initWithPost: (NSString *)post
            script : (NSString *)script
{
    self = [super init];
    if (self) {
        self->_postString = post;
        self->_script = script;
        self->_connection =
            [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
        self->_mutableReceivedData = [NSMutableData new];
    }
    //Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    //You need to send the actual length of your data. Calculate the length of the post string.
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    //Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string.
    //Create URLRequest object and initialize it.
    self.request = [[NSMutableURLRequest alloc] init];
    // make a string with the url
    NSString *url = [@"www.mySite.com/" stringByAppendingString:script];
    NSLog(@"%@", url);
    // Set the Url for which your going to send the data to that request.
    [self.request setURL:[NSURL URLWithString:url]];
    //Now, set HTTP method (POST or GET).
    [self.request setHTTPMethod:@"POST"];
    //Set HTTP header field with length of the post data.
    [self.request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    //Also set the Encoded value for HTTP header Field.
    [self.request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    // Set the HTTPBody of the urlrequest with postData.
    [self.request setHTTPBody:postData];
    return self;
}
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
    [self.mutableReceivedData setLength:0];
    NSLog(@"didReceiveRespongs");
}
- (void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)data
{
     [self.mutableReceivedData appendData:data];
    NSLog(@"didReceiveData");
}
- (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *)error
{
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"connectionFinished"
        object:self userInfo:@{@"error":error}];
    NSLog(@"-connection:didFailWithError: %@", error.localizedDescription);
}
- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"connectionFinished" object:self];
    NSLog(@"didFinishLoading");
}
- (void) cancel
{
    // cancel download in progress, replace connection, start over
    [self.connection cancel];
    self->_connection =
        [[NSURLConnection alloc] initWithRequest:self->_request delegate:self startImmediately:NO];
}
@end

三件事:

  1. 您配置NSURLRequest URL 的方式无效。此行缺少 URL 方案:

    NSString *url = [@"www.example.com/" stringByAppendingString:script];
    

    并且应该是:

    NSString *url = [@"http://www.example.com/" stringByAppendingString:script];
    
  2. initWithPost:Script: 中,您正在创建一个具有 nil 的请求对象的 NSURLConnection 对象。这一行:

    self->_connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
    

    应该移到[self.request setHTTPBody:postData];之后的行。

  3. initWithPost:Script:中,使用self->是不必要的。您可以简单地访问ivars _postString,等等。

最新更新