【问题标题】:Writing an iOS http Post class编写 iOS http Post 类
【发布时间】:2014-01-02 06:55:15
【问题描述】:

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

【问题讨论】:

  • 在 php 端打印你的 $_POST 数组并分享你得到的结果
  • 只需点击我提供的链接,您就会在浏览器中看到它。正如我在帖子中提到的,我在模拟器中什么都没有。
  • 是的,但我想知道这是 php 获取您试图从目标 c 发送的数据

标签: ios http http-post


【解决方案1】:

三件事:

  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->。您可以简单地以_postString 等方式访问 ivars。

【讨论】:

  • 谢谢!这解决了问题。感激不尽!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多