iOS使用JSON参数从AFNetworking HTTP POST方法获取JSON响应

时间:2015-11-20 13:11:41

标签: ios iphone json post afnetworking-2

我在404张贴JSON参数时收到https://api.hackerearth.com/codemonk/v1/topic­detail/错误。服务器使用POST HTTP方法获取topic的详细信息&成功时,预计会有JSON响应。 POST参数是id对象的topic。 POST参数应为JSON格式。 我正在使用AFNetworking如下 -

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

NSDictionary *params = [NSDictionary dictionaryWithObject:@1 forKey:@"id"];

NSString *str = @"https://api.hackerearth.com/codemonk/v1/topic­-detail/";

NSString *encodedStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[manager POST:encodedStr
   parameters:params
      success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    NSLog(@"responseObject : %@",responseObject);


} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

    NSLog(@"error : %@", error.localizedDescription);

}];

这是常规的东西,但不知道为什么我现在似乎无法纠正它。我只收到404 Page Not Found错误。这肯定不是服务器端问题。有帮助吗?

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助。

AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

operationManagerInstance.requestSerializer = requestSerializer;

============= UPDATE

复制网址时我有404。这是因为topic-detail之间的连字符符号实际上不是连字符。这是一些不起作用的特殊角色。

https://api.hackerearth.com/codemonk/v1/topic - 细节/

相反,我删除了它并手动输入连字符,它工作正常。

答案 1 :(得分:1)

删除以下行

NSString *encodedStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

尝试以下方法:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

NSDictionary *params = [NSDictionary dictionaryWithObject:@1 forKey:@"id"];

NSString *str = @"https://api.hackerearth.com/codemonk/v1/topic­-detail/";

[manager POST:str
   parameters:params
      success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {

    NSLog(@"responseObject : %@",responseObject);


} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {

    NSLog(@"error : %@", error.localizedDescription);

}];