我們公司申請了一個請求發(fā)送手機短信的接口, 為了請求驗證碼的需求, 但是驗證碼這6位數(shù)需要移動端這邊生成, 而且此接口GET/POST皆可, 采取的是拼接網(wǎng)址的形式, 參數(shù)字典填空即可. 最后返回的數(shù)據(jù)格式竟是純文本.
感謝http://www.cnblogs.com/JM110/p/5547169.html
http://blog.csdn.net/cuibo1123/article/details/40938225
其中一個參數(shù)是將申請下來的用戶id和密碼拼接在一起, 然后經(jīng)過MD532位小寫加密, 再作為參數(shù)內(nèi)容.
(CC_LONG)這個修飾不加會有黃色報警
#pragma mark - md5 32位小寫加密
+ (NSString *)md5SecureIn32LowCased:(NSString *)str{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",result[0], result[1], result[2], result[3],result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]];
}
我使用AFN3.x進行的網(wǎng)絡(luò)請求, 請求之前, 要對AFHTTPSessionManager進行這些設(shè)置
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: @"text/plain", nil];
而且還需要對拼接后的url字符串進行這一步操作, 不然直接崩在afn里面
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
這個接口請求成功后, 接口文檔說是返回純文本格式, 但打印出來是類似于<1233 1231 1231>的東西, 內(nèi)容我是拿臉敲的. 我們知道這是NSData, 需要轉(zhuǎn)成字符串才看得懂.
首先我們對這個data進行過濾, 過濾掉非utf-8的東西, 再進行轉(zhuǎn)化.
//注意:如果是三字節(jié)utf-8梯澜,第二字節(jié)錯誤痹兜,則先替換第一字節(jié)內(nèi)容(認為此字節(jié)誤碼為三字節(jié)utf8的頭)瑰妄,然后判斷剩下的兩個字節(jié)是否非法剩辟;
+ (NSData *)replaceNoUtf8:(NSData *)data{
char aa[] = {'A','A','A','A','A','A'}; //utf8最多6個字符辕近,當(dāng)前方法未使用
NSMutableData *md = [NSMutableData dataWithData:data];
int loc = 0;
while(loc < [md length])
{
char buffer;
[md getBytes:&buffer range:NSMakeRange(loc, 1)];
if((buffer & 0x80) == 0)
{
loc++;
continue;
}
else if((buffer & 0xE0) == 0xC0)
{
loc++;
[md getBytes:&buffer range:NSMakeRange(loc, 1)];
if((buffer & 0xC0) == 0x80)
{
loc++;
continue;
}
loc--;
//非法字符孕锄,將這個字符(一個byte)替換為A
[md replaceBytesInRange:NSMakeRange(loc, 1) withBytes:aa length:1];
loc++;
continue;
}
else if((buffer & 0xF0) == 0xE0)
{
loc++;
[md getBytes:&buffer range:NSMakeRange(loc, 1)];
if((buffer & 0xC0) == 0x80)
{
loc++;
[md getBytes:&buffer range:NSMakeRange(loc, 1)];
if((buffer & 0xC0) == 0x80)
{
loc++;
continue;
}
loc--;
}
loc--;
//非法字符座掘,將這個字符(一個byte)替換為A
[md replaceBytesInRange:NSMakeRange(loc, 1) withBytes:aa length:1];
loc++;
continue;
}
else
{
//非法字符,將這個字符(一個byte)替換為A
[md replaceBytesInRange:NSMakeRange(loc, 1) withBytes:aa length:1];
loc++;
continue;
}
}
return md;
}
最后將過濾完的data轉(zhuǎn)成utf-8形式的字符串, 就終于是我們?nèi)四芸炊奈淖至?/p>
NSString *str = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];