【问题标题】:How to get the Response Data using REST API url in ios如何在 ios 中使用 REST API url 获取响应数据
【发布时间】:2016-04-27 14:40:00
【问题描述】:

如何在 iOS 中从 REST API url 获取响应数据。

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

提前致谢

【问题讨论】:

  • 您想从 REST API 打印文本字段或标签上的数据?
  • @Abhi 我想在控制台打印数据

标签: ios objective-c rest oauth


【解决方案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);
         }];

【讨论】:

    【解决方案2】:

    您可以使用下面的代码从 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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是 Swift 3.0 的答案: 斯威夫特 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 2015-05-13
        • 1970-01-01
        • 2022-12-02
        相关资源
        最近更新 更多