使用 Objective-C 发送 HTTP GET 请求
Sending HTTP GET Request using Objective-C
我需要从 Parse API 查询一些数据。下面的代码是来自 Parse 的 CURL 示例:
curl -X GET \
-H "X-Parse-Application-Id: XXXXX" \
-H "X-Parse-REST-API-Key: XXXXX" \
-G \
--data-urlencode 'where={"key1":"value1","key2":"value2"}' \
https://api.parse.com/1/classes/ClassName
那么,这是我实现它的代码:
NSDictionary *dictionary = @{@"key1": @"value1", @"key1": @"value2"};
NSError *error = nil;
NSString *jsonString = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
if (!jsonData)
NSLog(@"Got an error: %@", error);
else
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *fullUrl = [NSString stringWithFormat:@"https://api.parse.com/1/classes/ClassName?where=%@", jsonString];
NSURL *url = [NSURL URLWithString:fullUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue:@"XXXXX" forHTTPHeaderField:@"X-Parse-Application-Id"];
[request addValue:@"XXXXX" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSLog(@"Data: %@", data);
NSLog(@"Response: %@", response);
}else{
NSLog(@"Error: %@", error);
}
}];
[task resume];
执行后出现一些错误:
2015-01-16 18:19:57.532 ParseTest[37964:1018046]
Error: Error Domain=NSURLErrorDomain Code=-1002
"The operation couldn’t be completed. (NSURLErrorDomain error -1002.)"
UserInfo=0x7d17d320 {NSUnderlyingError=0x7d051f70 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1002.)"}
完成过去的 CURL 代码的 Objective-C 等价物是什么?或者你有什么建议?
提前致谢。
您需要使用 PFQuery
。相关信息可在 Parse's iOS/OS X Documentation.
中找到
下面是一些示例代码,用于执行您在上面尝试的操作。它应该是那个 cURL 代码的直接替换:
- (void)runQuery {
PFQuery *query = [PFQuery queryWithClassName:@"ClassName"];
[query whereKey:@"key1" equalTo:value1];
[query whereKey:@"key2" equalTo:value2];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error != nil) {
// Do error handling here
} else {
// You have a valid query result
}
}
];
}
请不要忘记,您需要先在应用中初始化 Parse 连接,然后才能拨打电话。这样,您就不需要像在 cURL 代码中那样为每个请求传递密钥。您可以在 AppDelegate
对象的 -didFinishLaunchingWithOptions:
方法中执行此操作,如下所示:
#import <Parse/Parse.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize Parse.
[Parse
setApplicationId:@"<App Id>"
clientKey:@"<Client Key>"];
}
NSURLErrorDomain error -1002
表示 URL 不受支持。我的猜测是您需要 URL 为 where
参数编码您的 json。也许将您的 URL 更改为:
if (!jsonData)
NSLog(@"Got an error: %@", error);
else
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *fullUrl = [NSString stringWithFormat:@"https://api.parse.com/1/classes/ClassName?where=%@", jsonString];
如果这不起作用,您是否尝试过记录 fullUrl
并尝试 cURL
它?
我需要从 Parse API 查询一些数据。下面的代码是来自 Parse 的 CURL 示例:
curl -X GET \
-H "X-Parse-Application-Id: XXXXX" \
-H "X-Parse-REST-API-Key: XXXXX" \
-G \
--data-urlencode 'where={"key1":"value1","key2":"value2"}' \
https://api.parse.com/1/classes/ClassName
那么,这是我实现它的代码:
NSDictionary *dictionary = @{@"key1": @"value1", @"key1": @"value2"};
NSError *error = nil;
NSString *jsonString = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
if (!jsonData)
NSLog(@"Got an error: %@", error);
else
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *fullUrl = [NSString stringWithFormat:@"https://api.parse.com/1/classes/ClassName?where=%@", jsonString];
NSURL *url = [NSURL URLWithString:fullUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue:@"XXXXX" forHTTPHeaderField:@"X-Parse-Application-Id"];
[request addValue:@"XXXXX" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSLog(@"Data: %@", data);
NSLog(@"Response: %@", response);
}else{
NSLog(@"Error: %@", error);
}
}];
[task resume];
执行后出现一些错误:
2015-01-16 18:19:57.532 ParseTest[37964:1018046]
Error: Error Domain=NSURLErrorDomain Code=-1002
"The operation couldn’t be completed. (NSURLErrorDomain error -1002.)"
UserInfo=0x7d17d320 {NSUnderlyingError=0x7d051f70 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1002.)"}
完成过去的 CURL 代码的 Objective-C 等价物是什么?或者你有什么建议?
提前致谢。
您需要使用 PFQuery
。相关信息可在 Parse's iOS/OS X Documentation.
下面是一些示例代码,用于执行您在上面尝试的操作。它应该是那个 cURL 代码的直接替换:
- (void)runQuery {
PFQuery *query = [PFQuery queryWithClassName:@"ClassName"];
[query whereKey:@"key1" equalTo:value1];
[query whereKey:@"key2" equalTo:value2];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error != nil) {
// Do error handling here
} else {
// You have a valid query result
}
}
];
}
请不要忘记,您需要先在应用中初始化 Parse 连接,然后才能拨打电话。这样,您就不需要像在 cURL 代码中那样为每个请求传递密钥。您可以在 AppDelegate
对象的 -didFinishLaunchingWithOptions:
方法中执行此操作,如下所示:
#import <Parse/Parse.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize Parse.
[Parse
setApplicationId:@"<App Id>"
clientKey:@"<Client Key>"];
}
NSURLErrorDomain error -1002
表示 URL 不受支持。我的猜测是您需要 URL 为 where
参数编码您的 json。也许将您的 URL 更改为:
if (!jsonData)
NSLog(@"Got an error: %@", error);
else
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *fullUrl = [NSString stringWithFormat:@"https://api.parse.com/1/classes/ClassName?where=%@", jsonString];
如果这不起作用,您是否尝试过记录 fullUrl
并尝试 cURL
它?