如何使用AFNetworking设置请求的HTTP正文? [英] How to set the HTTP body for a request using AFNetworking?
问题描述
在AFNetworking的早期版本中,如果必须创建自己的自定义客户端,则只需从AFHTTPClient继承并创建我的方法。相信在AFNetworking 2.0中,我需要继承自AFHTTPSessionManager。
In the early versions of AFNetworking if I had to make my own custom client then I would simply inherit from AFHTTPClient and create my methods. In AFNetworking 2.0 I believe I need to inherit from AFHTTPSessionManager.
@interface MyCustomClient : AFHTTPSessionManager
{
}
在我的情况下,我需要以肥皂形式发送请求。这意味着HTTP正文将为soap,而HTTP HEADERS将为text / xml。
In my situation I need to send in request as soap. This means that HTTP Body will be soap and HTTP HEADERS will be text/xml.
假设我有一个变量,其中包含需要发送到服务器的整个肥皂主体。
Let's say I have a variable which contains the entire soap body I need to send to the server.
NSString *soapBody = @"Soap body";
使用上面定义的自定义类继承自AFHTTPSessionManager,如何将soap主体设置为Request HTTPBody 。
Using my custom class defined above which inherits from AFHTTPSessionManager how will I set the soap body to the Request HTTPBody.
如果仍然可以从AFHTTPSessionManager内部访问NSURLRequest,那么我可以简单地执行setHTTPBody,但是似乎没有?
If there is anyway to access NSURLRequest from inside the AFHTTPSessionManager then I can simply do setHTTPBody but it seems there is not?
我希望我现在明白了!
I hope I am making sense now!
推荐答案
您应该创建AFHTTPRequestSerializer的子类,然后实现协议AFURLRequestSerialization,该类将关心添加主体和请求的标头
You should create a subclass of AFHTTPRequestSerializer, then implement the protocol AFURLRequestSerialization, this class is going to care about adding the body and headers to the request
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError * __autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
[mutableRequest setValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[mutableRequest setHTTPBody:@"This is the soap Body!!"];
return mutableRequest;
}
您可以阅读实现或其他AFHTTPRequestSerializer子类https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLRequestSerialization.m#L1094
You can read the implementation or other AFHTTPRequestSerializer subclasses https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLRequestSerialization.m#L1094
这篇关于如何使用AFNetworking设置请求的HTTP正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!