gpt4 book ai didi

ios - AFNetworking (200-299) 中的预期状态代码,得到 403

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:52:08 25 4
gpt4 key购买 nike

尝试将我的代码从 ASIHttpRequest 迁移到 AFNetworking。似乎有人问过类似的问题,但无法找到我的问题的解决方案。

我的代码在 ASIHttpRquest 下运行良好。

我向我的服务器发送一个简单的 post 请求并监听 http 响应。如果 http response 是 200 一切正常,但如果我发送另一个状态代码 >400 AFNetworking block 失败。

服务器端响应:

$rc = $stmt->fetch();
if ( !$rc ) {
// echo "no such record\n";
$isrecordExist=0; //false does not exists
sendResponse(403, 'Login Failed');
return false;
}
else {
// echo 'result: ', $result, "\n";
$sendarray = array(
"user_id" => $result,
);
sendResponse(200, json_encode($sendarray));
}

IOS部分:

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:server]];
client.allowsInvalidSSLCertificate=YES;

[client postPath:loginForSavingCredientials parameters:params success:^(AFHTTPRequestOperation *operation, id response) {
if (operation.response.statusCode == 500) {}
else if (operation.response.statusCode == 403) {}
else if (operation.response.statusCode == 200) {//able to get results here NSError* error;
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"failure %@", [error localizedDescription]);
}];

NS日志:

 failure Expected status code in (200-299), got 403

我该如何解决这个问题?

最佳答案

AFNetworking 获得 2xx(成功)状态代码时,它会调用成功 block 。

当它收到 4xx(客户端错误)或 5xx(服务器错误)状态代码时,它会调用失败 block ,因为出了点问题。

因此,您需要做的就是将对 500 或 403 状态代码的检查移至失败 block 。

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:server]];
client.allowsInvalidSSLCertificate=YES;

[client postPath:loginForSavingCredientials parameters:params success:^(AFHTTPRequestOperation *operation, id response) {
if (operation.response.statusCode == 200) {//able to get results here NSError* error;
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"failure %@", [error localizedDescription]);
if (operation.response.statusCode == 500) {}
else if (operation.response.statusCode == 403) {}
}];

关于ios - AFNetworking (200-299) 中的预期状态代码,得到 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16845032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com