實在不曉得怎麼命名這篇技術文章,其實就是想要呼叫Web Service來取得資料,跟我過去平常使用的方式不太一樣,所以就特別來一篇記錄,未來就直接參考囉~
後台工程師特別使用x-www-form-urlencoded來呼叫此API,怎麼不跟之前一樣使用raw呢?下次來拷問他XD~強迫我一定要學新的實作方法!
就直接來看我怎麼成功寫這個method:
/** Theme: x-www-form-urlencoded IDE: Xcode 9 Language: Objective C Date: 107/03/11 Author: HappyMan Blog: https://cg2010studio.com/ */ - (void)searchPeopleWithInfoDict:(NSDictionary *)dict offset:(NSString *)offset success:(void (^)(NSDictionary *dict))successBlock fail:(void (^)(NSError *error))failBlock { NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; /* Create session, and optionally set a NSURLSessionDelegate. */ NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil]; NSString *subURLStr = [NSString stringWithFormat:@"api/v1/search/%@", offset]; NSURL* URL = [NSURL URLWithString: [APIBaseDomain stringByAppendingString:subURLStr]]; NSString *post =[NSString stringWithFormat:@"agemin=%@&agemax=%@&heightmin=%@&heightmax=%@&weightmin=%@&weightmax=%@", [dict[@"agemin"] description], [dict[@"agemax"] description], [dict[@"heightmin"] description], [dict[@"heightmax"] description], [dict[@"weightmin"] description], [dict[@"weightmax"] description]]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%ld",[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:URL]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request addValue:[@"" stringByAppendingString:[STUserDefaults sharedInstance].accessToken] forHTTPHeaderField:@"user"]; [request setHTTPBody:postData]; NSError *error; NSURLResponse *response; NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(@"str: %@", str); /* Start a new Task */ [self taskWithSession:session request:request success:^(NSDictionary *dict) { successBlock(dict); } fail:^(NSError *error) { failBlock(error); }]; }
最關鍵的地方就是在Header設定Content-Type為x-www-form-urlencoded。傳遞參數要使用ASCII編碼。
後來我發現Postman有工具可以幫我產生code,如此我就不用上網搜尋範例來趕。話說Chrome版本的Postman弱掉了,改用Mac版本的Postman能順利為我產出程式碼:
#import NSDictionary *headers = @{ @"user": @"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50IjoiamltbXlrbyIsImV4cCI6MTUxODE4ODA4NywiaWQiOjF9.6wtHIvrLVZej5fsHRkUa9UUa-viIbXrrPW12uYLRHQMX", @"Cache-Control": @"no-cache", @"Postman-Token": @"339f6c7e-d45a-4f45-8d2f-6586426068aex", @"Content-Type": @"application/x-www-form-urlencoded" }; NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"agemin=20" dataUsingEncoding:NSUTF8StringEncoding]];<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span> [postData appendData:[@"&agemax=100" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&heightmin=100" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&heightmax=180" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&weightmin=32" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&weightmax=100" dataUsingEncoding:NSUTF8StringEncoding]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.happydate.com/api/v1/search/0"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; [request setAllHTTPHeaderFields:headers]; [request setHTTPBody:postData]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }]; [dataTask resume];
讓懶人如我者可以省去不少嘗試時間!
參考:[iOS] WebView 解決網頁亂碼問題、POST request using application/x-www-form-urlencoded。
隨意留個言吧:)~