编写iOS http Post类

时间:2014-01-02 06:55:15

标签: ios http http-post

我正在尝试编写一个可用于发出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];

}

MyDownloader.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 个答案:

答案 0 :(得分:2)

三件事:

  1. 您为NSURLRequest配置网址的方式无效。这一行缺少URL方案:

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

    应该是:

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

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

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

  3. initWithPost:Script:中,无需使用self->。您可以简单地以_postString等方式访问ivars。