NSURLRequest POST 中文参数编码

NSString *postString = [NSString stringWithFormat:@"name=%@",@"张三"];

    NSData *postData = [postString dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion: YES];

    上面用NSUTF8StringEncoding编码POST的中文参数,得不到数据,因为服务器解码出来是乱码,要使用下面得编码方法:

    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingMacChineseSimp);
    NSData *postData = [postString dataUsingEncoding: enc allowLossyConversion: YES];

     NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    NSString *httpUrl = [NSString stringWithFormat:@"%@",SERVERADDRESS];
    NSURL *baseUrl = [NSURL URLWithString: httpUrl];
        
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:baseUrl
                                                                   cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                               timeoutInterval:20.0f];
    
    
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue: IPADDRESS forHTTPHeaderField:@"Host"];
    [urlRequest setValue: postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody: postData];
    
    NSError *error = nil;
    NSHTTPURLResponse *response = nil;
    NSData *urlData = [NSURLConnection 
                       sendSynchronousRequest:urlRequest 
                       returningResponse: &response 
                       error: &error];

你可能感兴趣的:(NSURLRequest POST 中文参数编码)