写在前面:以前都没有遇到过调用webservice接口的请求,这次遇到了记录一下。首先感谢原作者并附上原文http://www.cocoachina.com/bbs/read.php?tid-456019.html
如若着急解决手上问题可直接往下看。
这里利用最新的第三方网络请求框架AFN3.0
//常规的get请求
- (void)getUsersOfDept:(NSString *)deptId completeHandler:(UsersCompleteHandler)handler{
NSString *urlStr = [NSString stringWithFormat:[self joinURL:GETUSERSOFDEPTURL], deptId];
[[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSNumber *statusNumber = [responseObject objectForKey:@"Status"] ;
if (statusNumber == nil || [statusNumber integerValue] !=0) {
NSLog(@"load users of dept failed with result %@", responseObject);
handler(nil, nil);
} else {
NSArray *users = [responseObject objectForKey:@"Users"];
handler(users, nil);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"get users of dept %@", error.localizedDescription);
handler(nil, error);
}];
}
// 利用AFN manager请求webservice接口
+ (void)sendRequestWithURL:(NSString *)url xmlDocument:(DDXMLDocument *)doc
success:(void (^)(NSURLSessionDataTask * _Nonnull operation, id _Nonnull responseObject)) successHandler
failure:(void (^)(NSURLSessionDataTask * _Nonnull operation, NSError * _Nonnull error)) failureHandler{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// [manager.requestSerializer setValue:@"text/xml;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// 设置HTTPBody
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
return doc.XMLString;
}];
[manager POST:url parameters:doc.XMLString progress:nil success:successHandler failure:failureHandler];
}