Friday, July 25, 2014

Fetch gzip format response

@try {
        NSURL *url = [NSURL URLWithString:strURL];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  timeoutInterval:180.0];
        
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        
        //Set GZIP format
        [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        
        //Set Authorization request
        if([basicAuthRequired caseInsensitiveCompare:@"Yes"] ==  NSOrderedSame) {
            
            NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
            NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
            NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
            
            [request setValue:authValue forHTTPHeaderField:@"Authorization"];
        }
        
        NSURLResponse *response = NULL;
        NSError *requestError = NULL;
        
        //NSURLConnection will automatically decode gzipped response
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
                                                                 error:&requestError];
        
        NSError *errorSuccess=nil;
        
        NSMutableDictionary  *dictionary = [[NSMutableDictionary alloc]
                                            initWithDictionary:[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&errorSuccess]];
        
        if (errorSuccess) { //Handle error if dictionary failed to generate
            [self showSecureServiceAlert];
        }
        
        return dictionary;
    }
    @catch (NSException *exception) {
        // Handle exception
        NSLog(@"Exception in fetchURLContent function");

    }

No comments:

Post a Comment