AFNetworking给了我未经授权的错误

时间:2016-01-12 05:29:50

标签: ios objective-c api afnetworking

这是我第一次在我的应用中使用AFNetworking。我已经使用pod安装了最新版本(3.0)。现在问题是网址在浏览器和邮递员工作正常,但当我在应用程序中尝试它时,它给了我未经授权的错误。我不知道如何授权。我在标题中添加用户名和密码。有谁能够帮我。 贝娄是我的代码。

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"; } },

4 个答案:

答案 0 :(得分:0)

尝试使用此代码在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) {

    }];

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

这是因为:

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

格式Content-Type“=”text / html没有您的AFNetworking。

所以,只需转到 Serilization-&gt; AFURLResponseSerialization.m ,第215行,然后进行更改:

self.acceptableContentTypes = [NSSet setWithObjects:@“application / json”,@“text / json”,@“text / javascript”,@“text / html”,nil]; < / p>

它适合你。

更新的版本可能包含第223行的代码

答案 3 :(得分:0)

问题似乎出在你的请求编制中。根据错误日志,请设置请求内容类型,auth标头和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];