2

我无法将异步 NSURLRequests 发送到 Ruby 服务器。当我使用以下内容时,永远不会建立连接:

self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"form-data" forHTTPHeaderField:@"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

但是,当我交换最后一行时:

NSData *returnData = [NSURLConnection sendSynchronousRequest:request   returningResponse:nil error:nil];

一切都很好。但我确实需要异步建立这个连接......

编辑工作示例

NSURL *url = [NSURL URLWithString:@"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:@"data"];
[request setDelegate:self];
[request startAsynchronous];

在这种情况下,RESTful 服务似乎需要自己的第三方框架。

4

1 回答 1

6

你可以尝试使用 restkit api

- (void)sendAsJSON:(NSDictionary*)dictionary {

RKClient *client = [RKClient clientWithBaseURL:@"http://restkit.org"];        

// create a JSON string from your NSDictionary 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];

// send your data
if (!error)
     [[RKClient sharedClient] post:@"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
 }

参考:

  1. https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
  2. https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON

谢谢尼基尔

于 2012-07-26T08:56:58.600 回答