导航

RestKit学习2:使用RestKit发送和接受请求

Posted on 2012-08-01 15:13  蝈蝈俊  阅读(1677)  评论(1编辑  收藏  举报

首先请看本系列的上一篇文章:RestKit学习1:引用RestKit项目 ,这篇文章是RestKit的简单使用介绍。

参考:https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit

RestKit 支持网络层的请求,网络层的功能包括:建立和调度网络请求,以及请求结果响应处理。

一般来说,我们用RKClient来处理这些请求。RKClient 是一个可以连接到指定服务器的客户端对象。它初始化基本URL,HTTP头,验证信息。它支持两种验证:HTTP Authentication 和 OAuth。你可以初始化很多实例,当然也有一个全局的单件实例,全局的单件实例常常在应用的applicationDidFinishLaunching:withOptions方法中出现:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    [RKClient clientWithBaseURLString:@"http://www.in4s.cn:8080/Inpads/json"];

    NSLog(@"I am your RKClient singleton : %@", [RKClient sharedClient]);

    return YES;

}

发送请求以及接受请求代码:

 #import <RestKit/RestKit.h>

  // Here we declare that we implement the RKRequestDelegate protocol
  // Check out RestKit/Network/RKRequest.h for additional delegate methods
  // that are available.
  @interface RKRequestExamples : NSObject <RKRequestDelegate> {
  }

  @end

  @implementation RKRequestExamples

  - (void)sendRequests {
    // Perform a simple HTTP GET and call me back with the results
    [ [RKClient sharedClient] get:@"/foo.xml" delegate:self];

    // Send a POST to a remote resource. The dictionary will be transparently
    // converted into a URL encoded representation and sent along as the request body
    NSDictionary* params = [NSDictionary dictionaryWithObject:@"RestKit" forKey:@"Sender"];
    [ [RKClient sharedClient] post:@"/other.json" params:params delegate:self];

    // DELETE a remote resource from the server
    [ [RKClient sharedClient] delete:@"/missing_resource.txt" delegate:self];
  }

  - (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
    if ([request isGET]) {
      // Handling GET /foo.xml

      if ([response isOK]) {
        // Success! Let's take a look at the data
        NSLog(@"Retrieved XML: %@", [response bodyAsString]);
      }

    } else if ([request isPOST]) {
      
      // Handling POST /other.json 
      if ([response isJSON]) {
        NSLog(@"Got a JSON response back from our POST!");
      }

    } else if ([request isDELETE]) {

      // Handling DELETE /missing_resource.txt
      if ([response isNotFound]) {
        NSLog(@"The resource path '%@' was not found.", [request resourcePath]);
      }
    }
  }

  @end

 

执行程序,我们可以通过NSLog输入的信息看到接受到的内容。

 

参考资料:

http://mobile.tutsplus.com/tutorials/iphone/restkit_ios-sdk/