gpt4 book ai didi

ios - iOS 5 HTTP查询与JSON对象

转载 作者:行者123 更新时间:2023-12-01 17:34:32 24 4
gpt4 key购买 nike

在iOS 5上,如何使用JSON对象查询Web服务?
我尝试了许多不同的方法,但无法使其正常工作。看来AFNetworkingRestKit框架是最简单的途径,但是我都没有经验。我也是iOS开发的新手。

这是一个有效的示例查询:

https://site.com/gis?QUERY={"ARGUMENTS":{"TO":{"OBJECT_TYPE":"BUILDING","OBJECT_ID":"1","TYPE":"IDENTIFIER"},"FROM":{"OBJECT_TYPE":"BUILDING","OBJECT_ID":"2","TYPE":"IDENTIFIER"},"PATHTYPES":["SIDEWALK"},"QUERYTYPE":"FINDPATH"}

最佳答案

创建一个url请求,请参见下面的示例。这将发布json数据。在您的情况下,您使用的是GET http方法,因此您无需发布json数据,只需将其包含在url中即可。请注意,我的一些变量声明未显示。

NSArray *keys = [NSArray arrayWithObjects:@"longitude", @"latitude", nil];
NSArray *objects = [NSArray arrayWithObjects:longitude, latitude, nil];

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
__jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
__jsonString = [[NSString alloc]initWithData:__jsonData encoding:NSUTF8StringEncoding];
}

// Be sure to properly escape your url string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:@"https://site.com...etc"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: __jsonData];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [__jsonData length]] forHTTPHeaderField:@"Content-Length"];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];

if (errorReturned) {
// Handle error.
}
else
{
NSError *jsonParsingError = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
}

关于ios - iOS 5 HTTP查询与JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com