2013-06-18 3 views
12

AFNetworkingを使用してHTTP PUTリクエストを作成して、CouchDBサーバーに添付ファイルを作成しようとしています。サーバーは、HTTP本体にbase64でエンコードされた文字列が必要です。 AFNetworkingを使用してHTTPボディをキー/値ペアとして送信せずにこの要求を行うにはどうすればよいですか?AFNetworking - キー値のペアを使用せずに生データをPUTおよびPOSTするにはどうすればよいですか?

私はこの方法を見て、始めました:

- (void)putPath:(NSString *)path 
parameters:(NSDictionary *)parameters 
    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success 
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; 

しかし、ここでのパラメータは型であることになっている:NSDictionary。 HTTPボディにbase64でエンコードされた文字列を送信したいだけですが、キーには関連付けられません。誰かが適切な方法を教えてくれますか?ありがとう!

答えて

11

Hejaziの答えは簡単で、偉大な動作するはずです。

何らかの理由で、1つのリクエストに対して非常に具体的である必要がある場合(たとえば、ヘッダーなどをオーバーライドする必要がある場合など)、独自のNSURLRequestを作成することもできます。 base64DataFromStringavailable hereある

// Make a request... 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL]; 

// Generate an NSData from your NSString (see below for link to more info) 
NSData *postBody = [NSData base64DataFromString:yourBase64EncodedString]; 

// Add Content-Length header if your server needs it 
unsigned long long postLength = postBody.length; 
NSString *contentLength = [NSString stringWithFormat:@"%llu", postLength]; 
[request addValue:contentLength forHTTPHeaderField:@"Content-Length"]; 

// This should all look familiar... 
[request setHTTPMethod:@"POST"]; 
[request setHTTPBody:postBody]; 

AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure]; 
[client enqueueHTTPRequestOperation:operation]; 

NSDataのカテゴリ方法:

は、ここではいくつかの(未テスト)のサンプルコードです。

+0

uが私をここに助けることができます:http://stackoverflow.com/questions/22071188/afjsonparameterencoding-in-afnetworking-2-x-x – CRDave

+0

クライアントは、ここでは何ですか? –

+0

@ChitraKhatriそれは 'AFHTTPClient'インスタンスです(AFNetworking 1からは、AFNetworking 2には存在しません) –

4

次のようmultipartFormRequestWithMethodの方法を使用することができます。

NSURLRequest *request = [self multipartFormRequestWithMethod:@"PUT" path:path parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) { 
    [formData appendString:<yourBase64EncodedString>] 
}]; 
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure]; 
[client enqueueHTTPRequestOperation:operation]; 
0

私はAFNetworking 2.5.3を使用しており、AFHTTPRequestOperationManagerの新しいPOSTメソッドを作成しています。ここで

extension AFHTTPRequestOperationManager { 

    func POST(URLString: String!, rawBody: NSData!, success: ((AFHTTPRequestOperation!, AnyObject!) -> Void)!, failure: ((AFHTTPRequestOperation!, NSError!) -> Void)!) { 

     let request = NSMutableURLRequest(URL: NSURL(string: URLString, relativeToURL: baseURL)!) 
     request.HTTPMethod = "POST" 
     request.HTTPBody = rawBody 

     let operation = HTTPRequestOperationWithRequest(request, success: success, failure: failure) 

     operationQueue.addOperation(operation) 
    } 

} 
3

あなたは生のJSON送信する例があります。

NSDictionary *dict = ... 
NSError *error; 
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict 
                  options:NSJSONWritingPrettyPrinted 
                  error:&error]; 

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

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:YOUR_URL parameters:nil error:nil]; 

req.timeoutInterval = 30; 
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[req setValue:IF_NEEDED forHTTPHeaderField:@"Authorization"]; 

[req setHTTPBody:dataFromDict]; 

[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
    if (!error) { 
     NSLog(@"%@", responseObject); 
    } else { 
     NSLog(@"Error: %@, %@, %@", error, response, responseObject); 
    } 
}] resume]; 
1
NSData *data = someData; 
NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:   
[NSURL URLWithString:[self getURLWith:urlService]]]; 

[reqeust setHTTPMethod:@"PUT"]; 
[reqeust setHTTPBody:data]; 
[reqeust setValue:@"application/raw" forHTTPHeaderField:@"Content-Type"]; 

NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) { 

} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 

}]; 
[task resume]; 
0

法の下に使用してくださいを。

+(void)callPostWithRawData:(NSDictionary *)dict withURL:(NSString 
*)strUrl withToken:(NSString *)strToken withBlock:(dictionary)block 
{ 
NSError *error; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error]; 
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 
Please use below method. 
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:nil error:nil]; 

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue]; 
[req setValue:strToken forHTTPHeaderField:@"Authorization"]; 
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]]; 

[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 
    if (!error) { 
     if ([responseObject isKindOfClass:[NSData class]]) { 
      NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; 
      if ((long)[httpResponse statusCode]==201) { 
       NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
       [dict setObject:@"201" forKey:@"Code"]; 

       if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) { 
        NSDictionary *dictionary = [httpResponse allHeaderFields]; 
        NSLog(@"%@",[dictionary objectForKey:@"Location"]); 
        [dict setObject:[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"Location"]] forKey:@"Id"]; 
        block(dict); 
       } 
      } 
      else if ((long)[httpResponse statusCode]==200) { 
       //Leave Hours Calculate 
       NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil]; 
       block(serializedData); 
      } 
      else{ 
      } 
     } 
     else if ([responseObject isKindOfClass:[NSDictionary class]]) { 
      block(responseObject); 
     } 
    } else { 
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
     [dict setObject:ServerResponceError forKey:@"error"]; 
     block(dict); 
    } 
}] resume]; 
} 
関連する問題