网络请求设置AuthorizationHeader

NSURLConnection设置AuthorizationHeader

- (void)requestHeader {
    
    //请求参数
    NSMutableData*postData=[[NSMutableData alloc] init];
    [postData appendData:[[NSString  stringWithFormat:@"&username=%@",@"传给服务端的参数"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[[NSString  stringWithFormat:@"&password=%@",@"传给服务端的参数"] dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *urlstring=[NSString stringWithFormat:@"%@%@",@"http://123.456.789",@"/login"];
    NSURL *url = [NSURL URLWithString:urlstring];
    //请求配置
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSDictionary *headers = @{@"content-type": @"application/x-www-form-urlencoded"};
    [request setAllHTTPHeaderFields:headers];
    NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"服务端约定的参数", @"服务端约定的参数"];
    NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64Encoding]];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];
    //
    [request setHTTPBody:postData];
    //发起请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new]  completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@",connectionError);
        if (connectionError==nil) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@",dict);
        }
    }];
}

AFNetWorking设置AuthorizationHeader

AFNetWorking 3.0之前设置请求头

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  

[manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];  

[manager.requestSerializer = [AFJSONRequestSerializer serializer];  

[manager.responseSerializer = [AFJSONResponseSerializer serializer];  

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];  

[manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

AFNetWorking 3.0之后设置请求头,更加详细,POST和GET都可以

-(AFHTTPSessionManager*)defaultHTTPManager
{
    // 初始化对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 返回的格式 JSON
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    // 可接受的文本参数规格
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    
    // 开始设置请求头
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"填写系统版本" forHTTPHeaderField:@"sysVersion"];
    [manager.requestSerializer setValue:@"填写设备" forHTTPHeaderField:@"deviceModel"];
    [manager.requestSerializer setValue:@"填写App版本" forHTTPHeaderField:@"appVersion"];
    
    // uid是每个用户对应的ID  cipherText是密码
    NSString * part1 = [NSString stringWithFormat:@"%lld:%@",uid,cipherText];
    // 通过 ID :密码 的格式,用Basic 的方式拼接成字符串
    NSString * authorization = [NSString stringWithFormat:@"Basic %@",[part1 base64Encode]];
    // 设置Authorization的方法设置header
    [manager.requestSerializer setValue:authorization forHTTPHeaderField:@"Authorization"];
    // 或者直接调用AF的方法进行设置
//    - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
//       password:(NSString *)password
//    {
//        NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
//        NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
//        [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"];
//    }
    return manager;
}
看下例子


{

            Accept = "*/*";

            "Accept-Encoding" = "gzip, deflate";

            "Accept-Language" = "en;q=1";

            Appversion = "2.1.0";

            Authorization = "Basic ODE2NDY6ZG15T29UdXdqV3h5Q3MyUVFsS2FGY1NMN0lPclNnT0ZnTXg2b2hKVE5vNUtRNElNT1FhOHg0ZG1XdlVxQkR3QnRTNURLL2h4WmJtY0REWmowL05PbmluQ1AzbmtEZUJkTE82QXV5a3NQd2Jna1hzeEtXcTRIVUkrbHR0Qi8xeGhIYW5UNWJMUk0xZGpNUmtPWVRJSlJoMWhHSkQzaE54b3JSVFZCd2JSbnlrPQ==";

            Connection = "keep-alive";

            "Content-Length" = 452;

            "Content-Type" = "application/x-www-form-urlencoded";

            Cookie = "twt__Session=dedk2qi0prmill5okqu6hkdjc0; twt__nick_name=Ioiiii; twt__user_name=13826241102; twt__userid=81646; twt__user_login=26DHlY-ObWNrmWdRa5DXqMbTwqPDz5yOj41kmZlimGmaaJRnZIRwX6XGpKOn0tSZv76ObcjEmWZkl5mdxJSSmZlwxm1kxmWTZsaWZ2aVxJmZlpNWnY-rmZ_HkcOMYZZum2eYa2uWZ2BnmGpk";

            Devicemodel = "x86_64";

            Host = "u.taowaitao.cn";

            "If-Modified-Since" = "Wed, 28 Sep 2016 09:37:40 GMT";

            Sysversion = "ios10.0";

            "User-Agent" = "Taowaitao/2.1.0 (iPhone; iOS 10.0; Scale/2.00)";

        }


base64

系统base64
NSString* authStrData = [[NSString alloc] initWithData:[authData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSASCIIStringEncoding];
自定义base64
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation Base64
+(NSString *)encode:(NSData *)plainText {
    int encodedLength = (((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1;
    unsigned char *outputBuffer = malloc(encodedLength);
    unsigned char *inputBuffer = (unsigned char *)[plainText bytes];

    NSInteger i;
    NSInteger j = 0;
    int remain;

    for(i = 0; i < [plainText length]; i += 3) {
        remain = [plainText length] - i;

        outputBuffer[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];
        outputBuffer[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | 
                                     ((remain > 1) ? ((inputBuffer[i + 1] & 0xF0) >> 4): 0)];

        if(remain > 1)
            outputBuffer[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)
                                         | ((remain > 2) ? ((inputBuffer[i + 2] & 0xC0) >> 6) : 0)];
        else 
            outputBuffer[j++] = '=';

        if(remain > 2)
            outputBuffer[j++] = alphabet[inputBuffer[i + 2] & 0x3F];
        else
            outputBuffer[j++] = '=';            
    }

    outputBuffer[j] = 0;

    NSString *result = [NSString stringWithCString:outputBuffer length:strlen(outputBuffer)];
    free(outputBuffer);

    return result;
}
@end

参考https://stackoverflow.com/questions/1973325/nsurlconnection-and-basic-http-authentication-in-ios
http://blog.csdn.net/deft_mkjing/article/details/51900737

你可能感兴趣的:(网络请求设置AuthorizationHeader)