Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

ios - AFNetworking - How can I PUT and POST raw data without using a key value pair?

I am trying to make an HTTP PUT request using AFNetworking to create an attachment in a CouchDB server. The server expects a base64 encoded string in the HTTP body. How can I make this request without sending the HTTP body as a key/value pair using AFNetworking?

I began by looking at this method:

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

But here the parameters are to be of type: NSDictionary. I just want to send a base64 encoded string in the HTTP body but not associated with a key. Can someone point me to the appropriate method to use? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hejazi's answer is simple and should work great.

If, for some reason, you need to be very specific for one request - for example, if you need to override headers, etc. - you can also consider building your own NSURLRequest.

Here's some (untested) sample code:

// 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];

The NSData category method base64DataFromString is available here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...