如何使用ios中的REST API URL获取响应数据

时间:2016-01-21 11:14:45

标签: ios objective-c rest oauth

如何从iOS中的REST API网址获取响应数据。

enter image description here

NSURL *url = [NSURL URLWithString:@"http://sssssssssssssssss"];
//NSData * JSONdata = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
        NSString *headerValue = [NSString stringWithFormat:@"%@" , testToken];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:JSONBody];
        [request addValue:headerValue forHTTPHeaderField:@"oauth_token"];
        // examine the response

先谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用以下代码从REST API获取数据

{
NSString *post = [NSString stringWithFormat:@"parameter1=%@&parameter2=%@&parameter3=%@",parameter1txt]; // <--here put the request parameters you used to get the response


    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://your api"]];

    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
   //NSLog(@"str : %@",str);

    dict6 = [self cleanJsonToObject:responseData];
    NSLog(@"str : %@",dict6);
}

此处dict6为NSMutableDictionary,最后NSLOG将在控制台窗口中打印您的回复

- (id)cleanJsonToObject:(id)data
{
    NSError* error;
    if (data == (id)[NSNull null])
    {
        return [[NSObject alloc] init];
    }
    id jsonObject;
    if ([data isKindOfClass:[NSData class]])
    {
        jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    } else
    {
        jsonObject = data;
    }
    if ([jsonObject isKindOfClass:[NSArray class]])
    {
        NSMutableArray *array = [jsonObject mutableCopy];
        for (int i = (int)array.count-1; i >= 0; i--)
        {
            id a = array[i];
            if (a == (id)[NSNull null])
            {
                [array removeObjectAtIndex:i];
            } else
            {
                array[i] = [self cleanJsonToObject:a];
            }
        }
        return array;
    } else if ([jsonObject isKindOfClass:[NSDictionary class]])
    {
        NSMutableDictionary *dictionary = [jsonObject mutableCopy];
        for(NSString *key in [dictionary allKeys])
        {
            id d = dictionary[key];
            if (d == (id)[NSNull null])
            {
                dictionary[key] = @"";
            } else
            {
                dictionary[key] = [self cleanJsonToObject:d];
            }
        }
        return dictionary;
    } else
    {
        return jsonObject;
    }
}

答案 1 :(得分:0)

这是Swift 3.0的答案: Swift 3.0

let request = NSMutableURLRequest(url: NSURL(string: "http://httpstat.us/200")! as URL)
let session = URLSession.shared
request.httpMethod = "POST"
let params = ["username":"username", "password":"password"] as Dictionary<String, String>
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
      if error != nil {
          print("Error: \(String(describing: error))")
      } else {
          print("Response: \(String(describing: response))")
      }
 })

 task.resume()

答案 2 :(得分:-1)

使用https://github.com/AFNetworking/AFNetworking

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"yourURL.com"] parameters:@"Your pars to set it to nil"
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
          //here you can responseObject content that return from API 
            NSLog(@"responseObject: %@", responseObject);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"Error: %@", error);
         }];