首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用NSURLRequest在Http请求中发送json数据

如何使用NSURLRequest在Http请求中发送json数据
EN

Stack Overflow用户
提问于 2010-12-16 10:30:10
回答 5查看 117.9K关注 0票数 80

我是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"
}

提前谢谢你

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-12-17 09:11:39

下面是我要做的(请注意,发送到我的服务器的JSON需要是一个字典,对于key =quest..{:问题字典{ => }} ):

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%清楚,需要重新阅读,但一切都应该在这里让你入门。据我所知,这是异步的。在进行这些调用时,我的UI未被锁定。希望这能有所帮助。

票数 105
EN

Stack Overflow用户

发布于 2015-02-11 23:03:26

我为此挣扎了一段时间。在服务器上运行PHP。此代码将发布一个json,并从服务器获取json回复。

NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if ([data length] > 0 && error == nil){
         NSError *parseError = nil;
         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }
     else if ([data length] == 0 && error == nil){
         NSLog(@"no data returned");
         //no data, but tried
     }
     else if (error != nil)
     {
         NSLog(@"there was a download error");
         //couldn't download

     }
 }];
票数 7
EN

Stack Overflow用户

发布于 2013-11-12 22:49:47

到目前为止,你们中的大多数人已经知道了这一点,但我发布了这篇文章,以防万一,你们中的一些人仍然在为iOS6+中的JSON而苦苦挣扎。

在iOS6和更高版本中,我们使用的NSJSONSerialization Class速度很快,并且不依赖于包含“外部”库。

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

这是iOS6和更高版本现在可以解析JSON efficiently.The的方式。SBJson的使用也是ARC之前的实现,如果您在ARC环境中工作,也会带来这些问题。

我希望这能帮到你!

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4456966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档