向Objective-C中的API发出GET请求

问题描述 投票:0回答:2
curl -X GET  -H "X-Parse-Application-Id: XYZ"   -H "X-Parse-REST-API-Key: XYZ" -G  --data-urlencode 'where={"col1":"val1", "col2":"val2"}' https://api.parse.com/1/classes/ClassName/

我试图将以上curl命令转换为Objective-C中的以下代码,但无济于事。

responseData = [NSMutableData data];
NSString* classURL = @"https://api.parse.com/1/classes/ClassName/";
NSURL* url = [NSURL URLWithString:classURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
[request setValue:REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];

NSString *qryString = [NSString stringWithFormat:@"where={\"col1\":\"%@\", \"col2\":\"%@\"}", val1, val2];
[request setHTTPBody:[qryString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
                                                             delegate:self];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

NSString* resp = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(resp);
ios objective-c parse-platform
2个回答
0
投票

我已经制定了从解析中获取用户特定图像的方法。因此,您可以使用以下方法并根据需要进行修改。

//In below method I filtered object on objectID basis. So you have to change your filtering parameter
+(NSArray *)getObjectsWithObjectId:(NSString *)objectIdStr
{

  //Change below dictionary as per your need.
  NSDictionary *createdByDict = [[NSDictionary alloc] initWithObjectsAndKeys:objectIdStr,@"objectId",@"Pointer",@"__type",@"_User",@"className", nil];
 //In this above dict is added to create a final dict for sending as parameter for my result. So this depends upon ur parse db to change above and below dictionary.
 NSDictionary *paraDict = [[NSDictionary alloc] initWithObjectsAndKeys:createdByDict,@"createdBy", nil];


//Your dictionary would be like this one below, still check and change if needed.
//Also remove above to dictionary as they just your your reference. Might be useful for your further work in case of deeper filtering.
NSDictionary *paraDict = [[NSDictionary alloc]nitWithObjectsAndKeys:col1,val1,col2,val2, nil];

 NSError *error = nil;
 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paraDict options:0 error:&error];

 if (!jsonData){
    //NSlog(@"NSJSONSerialization failed %@", error);
 }

 NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
 NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:json, @"where", nil];

 NSString *urlStr = @"YOUR_URL";
 NSString *resultStr = [Utilities addQueryStringToUrlString:urlStr withDictionary:parameters];     //Method to collaborate urlStr with parameter and encode it as per standard. 

 NSURL *url = [NSURL URLWithString:resultStr];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 [request setHTTPMethod:@"GET"];
 [request addValue:PARSE_APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
 [request addValue:PARSE_REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];
 [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

 NSURLResponse* response;

 //Capturing server response
 NSData* data = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];

 NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

 NSArray *resultArray = [responseDictionary objectForKey:@"results"];

  if([responseDictionary objectForKey:@"error"]){
    [self showAlertWithTitle:@"ERROR" message:[responseDictionary objectForKey:@"error"]];
    return nil;
  }
 return resultArray;
}

//For parameter appending into url with encoding

+(NSString*)addQueryStringToUrlString:(NSString *)urlString withDictionary:(NSDictionary *)dictionary
{
  NSMutableString *urlWithQuerystring = [[NSMutableString alloc] initWithString:urlString];

 for (id key in dictionary) {
    NSString *keyString = [key description];
    NSString *valueString = [[dictionary objectForKey:key] description];

    if ([urlWithQuerystring rangeOfString:@"?"].location == NSNotFound) {
        [urlWithQuerystring appendFormat:@"?%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
    } else {
        [urlWithQuerystring appendFormat:@"&%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
    }
 }
 return urlWithQuerystring;
}

+(NSString*)urlEscapeString:(NSString *)unencodedString
{
  CFStringRef originalStringRef = (__bridge_retained CFStringRef)unencodedString;
  NSString *s = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,originalStringRef, NULL, NULL,kCFStringEncodingUTF8);
  CFRelease(originalStringRef);
 return s;
}

0
投票

感谢@ walle84。我花了一点时间研究它,并找出了Objective-C中的等效卷曲。

responseData = [NSMutableData data];

NSString* qryString = [NSString stringWithFormat:@"{\"col1\":\"%@\", \"col2\":\"%@\"}",
                       val1, val2];
NSString* escapedString = [qryString
                           stringByAddingPercentEncodingWithAllowedCharacters:
                           [NSCharacterSet URLHostAllowedCharacterSet]];
NSString* classURL = [NSString  stringWithFormat: @"https://api.parse.com/1/classes/ClassName/?where=%@", escapedString];
NSURL* url = [NSURL URLWithString:classURL];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:APP_ID forHTTPHeaderField:@"X-Parse-Application-Id"];
[request setValue:REST_API_KEY forHTTPHeaderField:@"X-Parse-REST-API-Key"];

NSError* error = [[NSError alloc] init];
NSHTTPURLResponse* responseCode = nil;
NSData* oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

if([responseCode statusCode] != 200)
{
    NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
    return nil;
}

NSString* response = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
© www.soinside.com 2019 - 2024. All rights reserved.