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

后端 未结 6 1008
执念已碎
执念已碎 2020-12-15 22:20

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 b

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 22:58

    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.

提交回复
热议问题