NSURLConnection连接到服务器,但不发布数据

时间:2013-08-30 21:51:33

标签: php ios objective-c http-post nsurlconnection

每当我尝试向PHP服务器发布内容时,都会收到以下消息。似乎代码连接到服务器,但没有返回数据,并且后期数据不会通过。它通过我制作的Java应用程序工作,所以我可以保证他们的PHP没有错。如果您可以帮助我,或者需要更多代码来帮助我,那就请求它。感谢。

以下是为NSURLConnection准备变量的代码:

NSString *phash = [NSString stringWithFormat:@"%d",phashnum];
        [phash stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
name = _nameField.text;
        [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        email = _emailField.text;
        [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

以下是我的NSURLConnection的代码:

NSString *urlPath = [NSString stringWithFormat:@"http://54.221.224.251"];
    NSURL *url = [NSURL URLWithString:urlPath];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];
    NSOperationQueue *queue= [[NSOperationQueue alloc]init];
    NSString *postData = [[NSString alloc] initWithString:stringdata];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if ([data length] > 0 && connectionError==nil){
            NSLog(@"Connection Success. Data Returned");
            NSLog(@"Data = %@",data);
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            int code = [httpResponse statusCode];
            NSString *coder = [NSString stringWithFormat:@"%d",code];
            NSLog(@"%@",coder);
        }
        else if([data length] == 0 && connectionError == nil){
            NSLog(@"Connection Success. No Data returned.");
            NSLog(@"Connection Success. Data Returned");
            NSLog(@"Data = %@",data);
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            int code = [httpResponse statusCode];
            NSString *coder = [NSString stringWithFormat:@"%d",code];
            NSLog(@"%@",coder);
        }
        else if(connectionError != nil && connectionError.code == NSURLErrorTimedOut){
            NSLog(@"Connection Failed. Timed Out");
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            int code = [httpResponse statusCode];
            NSString *coder = [NSString stringWithFormat:@"%d",code];
            NSLog(@"%@",coder);

        }
        else if(connectionError != nil)
        {
            NSLog(@"%@",connectionError);
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            int code = [httpResponse statusCode];
            NSString *coder = [NSString stringWithFormat:@"%d",code];
            NSLog(@"%@",coder);

        }
    }];

提前致谢。

2 个答案:

答案 0 :(得分:1)

“name =%@& email =%@& phash =%@”不是正确的网址编码字符串。每个键值对必须用'&'分隔字符,每个键的值由'='字符组成。通过用'+'字符替换空格然后用stringByAddingPercentEscapesUsingEncoding编码来转义键和值。

请参阅application/x-www-form-urlencoded

您可以在this blog post中找到如何执行此操作的配方。

答案 1 :(得分:1)

正如@elk所说,你应该用+替换空格。但是你应该对保留字符进行百分比编码(如RFC2396中所定义)。

不幸的是,标准stringByAddingPercentEscapesUsingEncoding没有逃脱所有保留字符的百分比。例如,如果名称是“Bill& Melinda Gates”或“Bill + Melinda Gates”,则stringByAddingPercentEscapesUsingEncoding不会逃脱&+(因此{{}} 1}}将被解释为空格,+将被解释为分隔下一个&参数。)

而是使用CFURLCreateStringByAddingPercentEscapes,在POST参数中提供必要的保留字符,然后用legalURLCharactersToBeEscaped替换空格。例如,您可以定义+类别:

NSString

注意,我主要关注的是@implementation NSString (PercentEscape) - (NSString *)stringForPostParameterValue:(NSStringEncoding)encoding { NSString *string = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@" ", (CFStringRef)@";/?:@&=+$,", CFStringConvertNSStringEncodingToEncoding(encoding))); return [string stringByReplacingOccurrencesOfString:@" " withString:@"+"]; } @end &字符,但RFC2396(取代RFC1738)将这些附加字符列为保留字段,因此包含它可能是谨慎的+中的所有保留字符。

将这一点拉到一起,我可能会将请求发布为:

legalURLCharactersToBeEscaped

使用实用方法:

NSDictionary *params = @{@"name" : _nameField.text ?: @"",
                         @"email": _emailField.text ?: @"",
                         @"phash": [NSString stringWithFormat:@"%d",phashnum]};

NSURL *url = [NSURL URLWithString:kBaseURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error)
        NSLog(@"sendAsynchronousRequest error = %@", error);

    if (data) {
        // do whatever you want with the data
    }
}];