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

iOS Get JSON response from AFNetworking HTTP POST method with JSON parameters

我在 https://api.hackerearth.com/codemonk/v1/topic­detail/ 上使用 JSON 参数发帖时遇到 404 错误。服务器使用 POST HTTP 方法获取 topic 的详细信息,成功时预计会有 JSON 响应。 POST参数是topic对象的id。 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 错误。这肯定不是服务器端问题。有帮助吗?

也许这会有所帮助。

AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];

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

operationManagerInstance.requestSerializer = requestSerializer;

=============更新

复制你的URL时我有404。这是因为主题详细信息之间的连字符实际上不是连字符。这是一些不起作用的特殊字符。

https://api.hackerearth.com/codemonk/v1/topic-详情/

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

删除以下行

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

}];