2013-03-24 137 views
3

我想用AFNetworking做一個包含GET和POST參數的POST請求。iOS AFNetworking GET/POST參數

我使用這個代碼:

NSString *urlString = [NSString stringWithFormat:@"upload_stuff.php?userGUID=%@&clientGUID=%@", 
          @"1234", 
          [[UIDevice currentDevice] identifierForVendor].UUIDString]; 

    NSString *newUrl = @"https://sub.domain.com"; 

    NSURL *baseURL = [NSURL URLWithString:newUrl]; 

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL]; 
    [httpClient defaultValueForHeader:@"Accept"]; 

    NSDictionary *getParams = [NSDictionary dictionaryWithObjectsAndKeys: 
          @"1234", @"userGUID", 
          [[UIDevice currentDevice] identifierForVendor].UUIDString, @"clientGUID", 
          nil]; 
    NSDictionary *postParams = [NSDictionary dictionaryWithObjectsAndKeys: 
           [@"xyz" dataUsingEncoding:NSUTF8StringEncoding], @"FILE", 
           nil]; 

    [httpClient postPath:urlString parameters:postParams success:^(AFHTTPRequestOperation *operation, id responseObject) { 


    }failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Error retrieving data: %@", error); 
    }]; 

現在我有兩個問題:

  • 我如何可以同時使用在相同的請求GET和POST詞典?目前,我正在將GET字典集成到URL中,並僅使用POST字典([httpClient postPath:...]

  • 我收到服務器錯誤,指出參數「FILE」丟失。不幸的是,我無法檢查任何服務器日誌(不是我的服務器)。但使用標準NSURLConnection我能夠發送請求與FILE參數到此服務器。那麼這裏出了什麼問題?

+0

Afnetworking有自己的發送文件的方法 – Horst 2013-03-25 03:32:03

+0

你可以給任何代碼嗎? – 2013-03-25 11:19:25

回答

0

#2你:

NSData* sendData = [self.fileName.text dataUsingEncoding:NSUTF8StringEncoding]; 
NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:sendData forKey:@"name"]; 
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl]; 
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" 
                     path:@"/photos" 
                   parameters:sendDictionary 
                constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
            {          
             [formData appendPartWithFileData:photoImageData 
                    name:self.fileName.text 
                   fileName:filePath 
                   mimeType:@"image/jpeg"]; 
            } 
            ]; 

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest]; 
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) { 

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite); 

}]; 

[operation setCompletionBlock:^{ 
    NSLog(@"%@", operation.responseString); //Gives a very scary warning 
}]; 

[operation start]; 

通過@Igor Fedorchuk從POST jpeg upload with AFNetworking

+0

答案與獲取參數沒有任何關係。它浪費了我的生命。 – OpenThread 2013-11-05 03:32:48

+1

其實,我不認爲GET方法可以直接發送文件。如果我錯了,請告訴我。 這個懶惰的答案發布爲@ user1423640的請求。這不是GET方法的答案。 如果您確實想通過GET方法發送它,請將圖像更改爲base64併發送。 (注意有限的長度) – Horst 2013-11-10 16:16:58

0

AFNetworking有沒有方法來設置GET和POST PARAMS。 你必須設置GET PARAMS到你的網址,並使用[AFHTTPClient requestWithMethod:path:parameters:]設置POST PARAMS。

- (NSURLRequest *)requestForPath:(NSString *)path method:(NSString *)method 
{ 
    NSMutableString *pathWithGetParams = [NSMutableString stringWithString:path]; 
    BOOL hasPathContainsQueryChar = [path rangeOfString:@"?"].location != NSNotFound; 
    [pathWithGetParams appendString:hasPathContainsQueryChar ? @"&" : @"?"]; 
    for (id key in self.getArguments.allKeys) 
    { 
     if ([key isKindOfClass:[NSString class]]) 
     { 
      NSString *value = self.getArguments[key]; 
      if ([value isKindOfClass:[NSString class]]) 
      { 
       [pathWithGetParams appendString:[[self class] urlEncode:key]]; 
       [pathWithGetParams appendString:@"="]; 
       [pathWithGetParams appendString:[[self class] urlEncode:value]]; 
       [pathWithGetParams appendString:@"&"]; 
      } 
     } 
    } 

    NSString *upperCaseMethod = [method uppercaseString]; 
    BOOL isMethodInGet = [upperCaseMethod isEqualToString:@"GET"]; 
    NSURLRequest *request = [[self shareAFClient] requestWithMethod:method 
                   path:pathWithGetParams 
                 parameters:isMethodInGet ? nil : self.postArguments]; 
    return request; 
} 

+ (NSString *)urlEncode:(NSString *)stringToEncode 
{ 
    return [self urlEncode:stringToEncode usingEncoding:NSUTF8StringEncoding]; 
} 

+ (NSString *)urlEncode:(NSString *)stringToEncode usingEncoding:(NSStringEncoding)encoding 
{ 
    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, 
                       (__bridge CFStringRef)stringToEncode, 
                       NULL, 
                       (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", 
                       CFStringConvertNSStringEncodingToEncoding(encoding)); 
} 

+ (NSString*)urlDecode:(NSString *)stringToDecode 
{ 
    return [self urlDecode:stringToDecode usingEncoding:NSUTF8StringEncoding]; 
} 

+ (NSString*)urlDecode:(NSString *)stringToDecode usingEncoding:(NSStringEncoding)encoding 
{ 
    return (__bridge_transfer NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, 
                            (__bridge CFStringRef)stringToDecode, 
                            (CFStringRef)@"", 
                            CFStringConvertNSStringEncodingToEncoding(encoding)); 
}