2015-05-24 29 views
0

我一直在嘗試使用HTTP POST請求的http://support.wan.travel/hc/en-us/articles/200191669實現Wego航班API。我只使用過GET請求,所以我在POST上做了一些閱讀,到目前爲止,我還沒有找到一種方法來發布請求,並在鏈接中顯示了一個包含飛行數據字典的請求(在objective-c中)以上:使用POST進行飛行API

POST api.wego.com/flights/api/k/2/searches 

{ 
    "trips": [ 
    { 
     "departure_code": "SYD", 
     "arrival_code": "LON", 
     "outbound_date": "2014-01-24", 
     "inbound_date": "2014-01-29" 
    } 
    ], 
    "adults_count": 1 
} 

我必須創建自己的NSDictionary,然後(分配?)它的請求,或者是有辦法格式化辭典成字符串?在此先感謝您的幫助:)

回答

0

你必須按照以下步驟創建POST數據:

NSDictionary *trips = [NSDictionary dictionaryWithObjectsAndKeys: 
         @"SYD", @"departure_code", 
         @"LON", @"arrival_code", 
         @"2014-01-24", @"outbound_date", 
         @"2014-01-29", @"inbound_date", 
         nil]; 
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys: 
         trips, @"trips", 
         @"1", @"adults_count", 
         nil]; 

NSError *jsonError = nil; 
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&jsonError]; 

然後進行POST請求:

NSURL *url = [[NSURL alloc] initWithString:@"http://api.wego.com/flights/api/k/2/searches"]; 
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15]; 
[urlRequest setHTTPMethod:@"POST"]; 

const char *parameters = [jsonData bytes]; 
NSData *postData = [[NSData alloc] initWithBytes:parameters length:strlen(parameters)]; 
[urlRequest setHTTPBody:postData]; 

NSURLResponse *response = nil; 
NSError *requestError = nil; 
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&requestError]; 
NSLog(@"%@", [NSString stringWithUTF8String:[data bytes]]);