2016-06-11 46 views
-1

我想問如何使用AFNetworking 3.0發送身體POST請求。 任何幫助將不勝感激!發送POST請求與身體字典在網絡3.0

+0

檢查AFNetworking文檔http://cocoadocs.org/docsets/AFNetworking/3.1.0/Classes/AFHTTPSessionManager html的。你可以使用方便的方法[AFHTTPSessionManager NSURLSessionDataTask *)POST:(NSString *)URLString參數:(可空的id)參數成功:(可空void(^)(NSURLSessionDataTask * task,id _Nullable responseObject))成功失敗:(可空void(^ )(NSURLSessionDataTask * _Nullable task,NSError * error))failure]。 – kaushal

回答

1

AFNetworking's GitHub:特別是如果你想設置一個自定義的請求主體

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; 

    //Set the request body here 

} error:nil]; 

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

NSURLSessionUploadTask *uploadTask; 
uploadTask = [manager 
      uploadTaskWithStreamedRequest:request 
      progress:^(NSProgress * _Nonnull uploadProgress) { 
       // This is not called back on the main queue. 
       // You are responsible for dispatching to the main queue for UI updates 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        //Update the progress view 
        [progressView setProgress:uploadProgress.fractionCompleted]; 
       }); 
      } 
      completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
       if (error) { 
        NSLog(@"Error: %@", error); 
       } else { 
        NSLog(@"%@ %@", response, responseObject); 
       } 
      }]; 

[uploadTask resume]; 

編輯

以上的答案是非常有用的。

如果您只需要發佈一個簡單的參數設置,你可以做這樣的:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]]; 

[manager POST:@"http://exaple.com/path" parameters:@{@"param1" : @"foo", @"anotherParameter" : @"bar"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { 

    //success block 

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 

    //failure block 

}]; 
+0

我想發佈一個字符串,它只是一個令牌而不是一個圖像 –