【问题标题】:AFNetworking give me unauthorised errorAFNetworking 给我未经授权的错误
【发布时间】:2016-04-16 15:04:24
【问题描述】:

这是我第一次在我的应用程序中使用AFNetworking。我已经使用 pods 安装了最新版本(3.0)。现在的问题是 url 在浏览器和邮递员中运行良好,但是当我在应用程序中尝试时,它给了我未经授权的错误。不知道怎么授权。我在标题中添加用户名和密码。有谁能够帮我。 下面是我的代码。

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager.requestSerializer setValue:username forHTTPHeaderField:@"username"];
[manager.requestSerializer setValue:password forHTTPHeaderField:@"password"];


[manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {

    success(responseObject);

} failure:^(NSURLSessionDataTask *task, NSError *error) {

    failure(error);

}];

以下是完整的错误日志

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)"
 UserInfo={NSUnderlyingError=0x7fa1c3f945b0 {Error
 Domain=com.alamofire.error.serialization.response Code=-1016 "Request
> failed: unacceptable content-type: text/html"
> UserInfo={com.alamofire.serialization.response.error.response=<NSHTTPURLResponse:
 0x7fa1c3d139f0> { URL:
 http://192.168.0.111/guesswhat/getcategories.json } { status code:
 401, headers {
         "Cache-Control" = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0";
         Connection = "Keep-Alive";
         "Content-Length" = 89;
        "Content-Type" = "text/html";
         Date = "Mon, 11 Jan 2016 12:30:55 GMT";
         Expires = "Thu, 19 Nov 1981 08:52:00 GMT";
         "Keep-Alive" = "timeout=5, max=99";
         Pragma = "no-cache";
         Server = "Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.5.19";
         "Www-Authenticate" = "Digest realm=\"Restricted area\",qop=\"auth\",nonce=\"5693a07f60c93\",opaque=\"cdce8a5c95a1427d74df7acbf41c9ce0\"";
 Blockquote     "X-Powered-By" = "PHP/5.5.19"; } },

【问题讨论】:

  • 请发布错误控制台日志,以便我们找到解决方案。
  • 好像您没有访问权限或纯凭据不正确
  • 重新检查username/password的值。
  • 用户名/密码正确。它在邮递员中工作。
  • 尝试打印 [[NSString alloc] initWithData:[error.userInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:4]

标签: ios objective-c api afnetworking


【解决方案1】:

试试这个代码在 NSDictionary 中发送你的参数。(你的代码中没有基本 url 也传递参数 nil)。

    NSDictionary *parameters;
    ///// HTTP GET REQUEST TO DELETE ARTWORK
        parameters = @{@"device_user_id": [[NSUserDefaults standardUserDefaults] objectForKey:@"UserID"],
                       @"device_auth_key": [[NSUserDefaults standardUserDefaults] objectForKey:@"AuthKey"],
                       @"query":@"",
                       @"user_id":[NSNumber numberWithInteger:[[[self.otherUserDictionary objectForKey:@"from_user"] objectForKey:@"id"] intValue]],
                       @"mobile_request":@"yes"};
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL_STRING]];//Here your base url string
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer =[AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
//   /search replace accordingly
    [manager GET:@"/search" parameters:parameters success:^(NSURLSessionDataTask *task, NSDictionary* responseObject) {

        //NSLog response object
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];

【讨论】:

  • 我们可以使用完整的 url 而无需指定基本 URL 也可以在请求参数中发送 nil
【解决方案2】:

尝试在请求序列化程序上设置“授权”字段的值。

[manager.requestSerializer setValue:@"AuthToken" forHTTPHeaderField:@"Authorization"];

【讨论】:

    【解决方案3】:

    因为这个而发生:

    NSLocalizedDescription=请求失败:不可接受的内容类型:文本/html

    format Content-Type" = "text/html 没有你的 AFNetworking。

    所以只需转到 Serilization->AFURLResponseSerialization.m,第 215 行并更改它:

    self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    它会为你工作。

    更新的版本可能在第 223 行有代码

    【讨论】:

    • 如果你想改变这个不需要编辑原始源,你可以使用 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:];
    【解决方案4】:

    问题似乎出在您的请求格式中。请根据错误日志,设置请求内容类型、auth header和http方法类型。服务大多使用 base64 字符串作为用户名和密码 auth 字段 示例代码:

        //base 64 auth value from username and password
        - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
                                               password:(NSString *)password
        {
            NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
            [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"];
        }
      // authValue is your base 64 string from username and password
         [manager.requestSerializer setValue:authValue forHTTPHeaderField:@"Authorization"];
         [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
          manager.requestSerializer = [AFJSONRequestSerializer serializer];
          manager.responseSerializer = [AFJSONResponseSerializer serializer];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-20
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      相关资源
      最近更新 更多