我尝试使用AFHTTPSessionManager向Web服务发送请求
这是我的问题:我想发送带有JSON格式参数的URL GET请求。 像这样: http://api.mysite.com/v2/json/search?parameters= {“API_KEY”:” YOUR_API_ 键”,”查询”:{‘perpage’:50}}
我已经将AFHTTPSessionManager子类化了。这是我的代码的样子:
+ (MyAPIClient *)sharedClient {
static MyAPIClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:kBaseURLString]];
});
return _sharedClient;
}
和初始化者:
- (instancetype)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.requestSerializer = [AFJSONRequestSerializer serializer];
return self;
}
所以我的表现如何:
- (void)sendMyQueryWithSuccess:
(void(^)(NSURLSessionDataTask *task, id responseObject))success
andFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure{
NSDictionary *params = @{@"api_key" : kAPIKey,
@"query": @{@"perpage": @50}};
NSString *paramsstring = [[NSString alloc]
initWithData:[NSJSONSerialization
dataWithJSONObject:params
options:0
error:nil]
encoding:NSUTF8StringEncoding];
NSString* path = [NSString stringWithFormat:@"search_sale?parameters=%@",paramsstring];
[self GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if (success) {
success(task, responseObject);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure) {
failure(task, error);
}
}];
}
我一直这样:
* 断言失败 - [AFJSONRequestSerializer requestWithMethod:URLString:parameters:error:],AFNetworking / AFNetworking / AFURLRequestSerialization.m:277
* 由于未捕获的异常终止应用' NSInternalInconsistencyException',原因:'无效的参数不满足:URLString'
那么这里的问题是什么?
当我打印" path"的值时我得到了我想要的东西:
search?parameters={"api_key":"SOME_API_KEY","query":{"perpage":10}}
非常感谢任何输入
答案 0 :(得分:8)
是的,你可以:
NSString *stringCleanPath = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
我不得不将它用于parse.com的rest api和AFNetworking,并且完美无缺。
答案 1 :(得分:2)
您无法将字典作为GET请求发送。您应该更改API以将参数检查为POST字典。您实际上要做的是发送上面的POST请求参数。
或者......您可能想要做的是将其更改为字符串:
NSString *params = [NSString stringWithFormat:@"\"api_key\":\"%@\",\"query\":{\"perpage\":%@}}", kAPIKey, @50];
但老实说,这有点混乱。