今天遇到一奇葩問(wèn)題:
在UITextField中輸入帳號(hào):189123456 密碼:123456
使用GET請(qǐng)求時(shí)拼接出來(lái)的URL為nil巢价,導(dǎo)致無(wú)法訪問(wèn)服務(wù)器
原因:在UITextField中輸入的數(shù)字可能是中文字符
解決辦法:拼接URL時(shí)將字符串 UTF-8轉(zhuǎn)碼
大致代碼如下:
//把傳進(jìn)來(lái)的URL字符串轉(zhuǎn)變?yōu)閁RL地址
+ (NSURLRequest *)request_URL:(NSString *)urlStr RequestParams:(NSDictionary *)params Method:(NSString *)method
{
//把傳進(jìn)來(lái)的URL字符串轉(zhuǎn)變?yōu)閁RL地址
NSURL *requestUrl;
//解析請(qǐng)求參數(shù),用NSDictionary來(lái)存參數(shù)因痛,通過(guò)自定義的函數(shù)parseParams把它解析成一個(gè)post格式的字符串
NSString *parseParamsResult = [self buildParams:params];
NSString *newUrlStr = [NSString stringWithFormat:@"%@?%@", urlStr, parseParamsResult];
if ([method isEqualToString:@"GET"])
{
requestUrl = [NSURL URLWithString:[newUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}else
{
requestUrl = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
//請(qǐng)求初始化,可以在這針對(duì)緩存昧廷,超時(shí)做出一些設(shè)置
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestUrl];
//設(shè)置請(qǐng)求方式post或者get
[request setHTTPMethod:method];
// 如果是post請(qǐng)求蝶防,設(shè)置其請(qǐng)求體
if ([method isEqualToString:@"POST"])
{
NSData *postData = [parseParamsResult dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
}
return request;
}