2014-10-20 46 views
0

我試圖與一些參數的POST請求,但沒有辦成,看看發佈請求NSURL/NSURLConnection不能在ios中工作?

#define kLatestKivaLoansURL [NSURL URLWithString: @"http://url...."] 

NSDictionary *params = @{@"medcine": @"xanax", @"lat": @"31.0000",@"long":@"74.0000",@"offset":@"0"}; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:kLatestKivaLoansURL]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:[self httpBodyForParamsDictionary:params]]; 
NSLog(@"%@",request); 

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    if (error) { 
     NSLog(@"dataTaskWithRequest error: %@", error); 
    } 

    if ([response isKindOfClass:[NSHTTPURLResponse class]]) { 
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; 
     if (statusCode != 200) { 
      NSLog(@"Expected responseCode == 200; received %ld", (long)statusCode); 
     } 
    } 
    }]; 
[task resume]; 
    - (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary 
{ 
    NSMutableArray *parameterArray = [NSMutableArray array]; 

[paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) { 
    NSString *param = [NSString stringWithFormat:@"%@=%@", key, [self percentEscapeString:obj]]; 
    [parameterArray addObject:param]; 
}]; 

NSString *string = [parameterArray componentsJoinedByString:@"&"]; 
NSLog(@"%@",string); 
return [string dataUsingEncoding:NSUTF8StringEncoding]; 

}

- (NSString *)percentEscapeString:(NSString *)string 
    { 
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, 
                      (CFStringRef)string, 
                      (CFStringRef)@" ", 
                      (CFStringRef)@":/[email protected]!$&'()*+,;=", 
                       kCFStringEncodingUTF8)); 
    NSLog(@"%@",result); 
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"]; 


} 

錯誤

APP[2866:154303] dataTaskWithRequest error: Error Domain=NSURLErrorDomain Code=-1003 "The operation couldn’t be completed. (NSURLErrorDomain error -1003.)" UserInfo=0x7874ef60 {NSErrorFailingURLStringKey=http://URL..., _kCFStreamErrorCodeKey=8, 
NSErrorFailingURLKey=http://URL..., _kCFStreamErrorDomainKey=12, NSUnderlyingError=0x78773e70 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1003.)"} 

回答

0

嘗試:更換下面的方法。

- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary 
{ 

NSError *error =nil; 
return [NSJSONSerialization dataWithJSONObject:paramDictionary 
                 options:0 
                 error:&error]; 
} 
0

此鏈接解釋錯誤代碼相當不錯,AppleDevDoc。以下是關於此錯誤的說明:

kCFURLErrorCannotFindHost = -1003 

我認爲域名是錯誤的。