我一直在尝试从http://support.wan.travel/hc/en-us/articles/200191669实施使用HTTP POST请求的Wego flight API。我之前只使用过GET请求,所以我在POST上做了一些阅读,到目前为止,我还没能找到一种方法来发布一个带有飞行数据字典的请求(在objective-c中),如图所示上面的链接:
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 :(得分: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]]);