如何使用NSURLRequest在http请求中发送json数据?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (45)

我是新来的Objective-C,并且我开始为最近的请求/响应付出很大的努力。我有一个可以调用url(通过http GET)并解析返回的json的工作示例。

下面的工作示例如下

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
  //do something with the json that comes back ... (the fun part)
}

- (void)viewDidLoad
{
  [self searchForStuff:@"iPhone"];
}

-(void)searchForStuff:(NSString *)text
{
  responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

我的第一个问题是 - 这种方法是否会扩大?或者,这不是异步(这意味着当应用程序正在等待响应时阻止UI线程)

我的第二个问题是 - 我如何修改这个请求部分来做POST而不是GET?是否只是像这样修改HttpMethod?

[request setHTTPMethod:@"POST"];

最后 - 我如何将一组json数据作为一个简单的字符串添加到这篇文章中(例如)

{
    "magic":{
               "real":true
            },
    "options":{
               "happy":true,
                "joy":true,
                "joy2":true
              },
    "key":"123"
}
提问于
用户回答回答于

以下是我所做的事情(请注意,去我的服务器的JSON需要是具有一个值(另一个字典)的字典,用于key = question..ie {:question => {dictionary}}):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

receivedData然后被处理:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

这不是100%清楚,需要一些重新阅读,但一切都应该在这里让你开始。据我所知,这是异步的。进行这些调用时,我的用户界面没有被锁定。希望有所帮助。

用户回答回答于

我会建议使用ASIHTTPRequest

ASIHTTPRequest是一个易于使用的CFNetwork API包装器,它使与Web服务器通信更加单调乏味。它是用Objective-C编写的,适用于Mac OS X和iPhone应用程序。 它适合执行基本的HTTP请求并与基于REST的服务(GET / POST / PUT / DELETE)交互。包含的ASIFormDataRequest子类可以使用multipart / form-data轻松提交POST数据和文件。

请注意,原作者已停止使用此项目。请查看后续文章,了解原因和备选方案:http://allseeing-i.com/%5Brequest_release%5D ;

就我个人而言,我是AFNetworking的忠实粉丝

扫码关注云+社区