我是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];
}

My first question is - will this approach scale up? Or is this not async (meaning I block the UI thread while the app is waiting for the response)

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

[request setHTTPMethod:@"POST"];

And finally - how do I add a set of json data to this post as a simple string (for example)

{
    "magic":{
               "real":true
            },
    "options":{
               "happy":true,
                "joy":true,
                "joy2":true
              },
    "key":"123"
}

提前谢谢

推荐答案

Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {: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];
}

The receivedData is then handled by:

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

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

Json相关问答推荐

使用相同的密钥值来命名Json并使用Jolt重命名密钥

对一些JSON模式验证的混淆

jq如何合并两个json对象

如何在 JSonPath 中按值查找列表中的所有元素

将环境变量值从 yaml 传递到 json

JSONPath:查找子项目条件在字符串列表中的项目

将请求中的数据推送到数组中

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

如何解决名为 null 的map值

如何使用 LINQ 在 C# 中重构对象?

缺少所需的请求正文内容:org.springframework.web.method.HandlerMethod$HandlerMethodParameter

如何将任意 json 对象发布到 webapi

未捕获的类型错误:无法读取 null 的属性props

Flask 请求和 application/json 内容类型

Python Flask-Restful POST 不采用 JSON 参数

.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

如何在 json 编码字符串内的子数组数据周围添加方括号?

未调用 npm package.json 脚本

如何从 JSON 响应中提取单个值?

Python 到 JSON 序列化在十进制上失败