栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我如何将json字符串发布到服务器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我如何将json字符串发布到服务器

当然,这是一个重复的问题,但这是完整的示例代码,作为一个长例程。只需复制并粘贴。

首先设置JSON …

-(void)sendTestJsonCommand    {    NSMutableDictionary *dict = @{        @"heights":@"4_5_7",        @"score":@"4",        @"title":@"Some Title",        @"textBody":@"Some Long Text",        @"happy":@"y"        }.mutableCopy;    NSError *serr;    NSData *jsonData = [NSJSonSerialization        dataWithJSONObject:dict options:NSJSonWritingPrettyPrinted error:&serr];    if (serr)        {        NSLog(@"Error generating json data for send dictionary...");        NSLog(@"Error (%@), error: %@", dict, serr);        return;        }    NSLog(@"Successfully generated JSON for send dictionary");    NSLog(@"now sending this dictionary...n%@nnn", dict);

接下来,正确异步地将命令和json发送到您的服务器…

#define appService [NSURL   URLWithString:@"http://www.corp.com/apps/function/user/pass/id/etc"]    // Create request object    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:appService];    // Set method, body & content-type    request.HTTPMethod = @"POST";    request.HTTPBody = jsonData;    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];    [request setValue:        [NSString stringWithFormat:@"%lu",        (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];    // you would almost certainly use MBProgressHUD at this point    // to display some sort of spinner or similar action on the UX

最后,(A)使用NSURLConnection正确连接,(B)正确解释从服务器返回给您的信息。

    [NSURLConnection sendAsynchronousRequest:request        queue:[NSOperationQueue mainQueue]        completionHandler:^(NSURLResponse *r, NSData *data, NSError *error)        {        if (!data) { NSLog(@"No data returned from server, error ocurred: %@", error); NSString *userErrorText = [NSString stringWithFormat:    @"Error communicating with server: %@", error.localizedDescription] return; }        NSLog(@"got the NSData fine. here it is...n%@n", data);        NSLog(@"next step, deserialising");        NSError *deserr;        NSDictionary *responseDict = [NSJSonSerialization     JSONObjectWithdata:data     options:kNilOptions     error:&deserr];        NSLog(@"so, here's the responseDictnnn%@nnn", responseDict);        // LOOK at that output on your console to learn how to parse it.        // to get individual values example blah = responseDict[@"fieldName"];        }];    }

希望它可以节省一些键入的时间!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427608.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号