AFNetworking — get redirect URL

被刻印的时光 ゝ 提交于 2019-12-07 13:13:32

问题


Use a AFNetworking against a REST API.

  • POST to resources/
  • Server responds with 303 -> see resources/3928.json

The the server is giving information here: the id 3928 has been assigned to your resource.

Is it possible to learn this URL during the POST operation? Also, I don't really need this resource. Can I avoid actually following the redirect?

Another option is to use a 200 with {status:"ok",insert_id:3928} but it feels like this is not necessary


回答1:


-(void)call
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:YOUR_PARAMETER forKey:KEY];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:YOUR_WEBSERVICE_URL];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:WEBSERVICE_NAME parameters:params];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //This is Redirect URL 
         NSLog(@"%@",[[[operation response] URL] absoluteString]);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Failure");
     }];

     [operation start];
}



回答2:


I know this is a bit old, but I ran into this same type of problem. What helped me achieve finding the redirect URL was the following code snippet. I was able to get my redirect url out of the jsonDict.

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id jsonObject){
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"json: %@", jsonDict);
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
    NSLog(@"failure");
}];


来源:https://stackoverflow.com/questions/16370109/afnetworking-get-redirect-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!