AFNetworking - 如何在不使用键值对的情况下PUT和POST原始数据? [英] AFNetworking - How can I PUT and POST raw data without using a key value pair?

查看:157
本文介绍了AFNetworking - 如何在不使用键值对的情况下PUT和POST原始数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AFNetworking 发出HTTP PUT请求,以在CouchDB服务器中创建附件。服务器需要HTTP主体中的base64编码字符串。如何在不使用 AFNetworking 将HTTP正文作为键/值对发送的情况下发出此请求?

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;

但这里的参数应为: NSDictionary 。我只想在HTTP主体中发送base64编码的字符串,但不与密钥相关联。有人能指出我使用的适当方法吗?谢谢!

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!

推荐答案

Hejazi的答案很简单,应该很有效。

Hejazi's answer is simple and should work great.

如果由于某种原因,您需要非常具体地针对一个请求 - 例如,如果您需要覆盖标题等 - 您还可以考虑构建自己的NSURLRequest。

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

NSData类别方法 base64DataFromString 此处可用

The NSData category method base64DataFromString is available here.

这篇关于AFNetworking - 如何在不使用键值对的情况下PUT和POST原始数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆