objective-c - 使用 Json 在 Objective C 中发布数据

我正在尝试将数据发布到 PHP 网络服务。
我很熟悉在 html 中使用查询 $.post 执行此操作,但我非常难以在 Objective-C 中尝试此操作。 我尝试了几个在 stackoverflow 上发现的博客和问题。

我终于想出了以下代码:

NSString *jsonRequest = [NSString stringWithFormat:@"{\"Email\":\"%@\",\"FirstName\":\"%@\"}",user,fname];
NSLog(@"Request: %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"http:myurl..."];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

[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 connectionWithRequest:request delegate:self];

我也试过了:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

我的网络服务在帖子中创建一个新用户并返回用户 ID。 两者都成功地进行了网络服务调用(创建了一个新的用户 ID),但是他们没有发布数据,即每次都创建一个空白用户。
如果我遗漏了什么,请告诉我。

谢谢。

我的其他尝试:

NSMutableURLRequest *request = 
[[NSMutableURLRequest alloc] initWithURL:
 [NSURL URLWithString:@"myUrl.. "]];

[request setHTTPMethod:@"POST"];

NSString *postString = @"Email=me@test.com&FirstName=Test";

[request setValue:[NSString 
                   stringWithFormat:@"%d", [postString length]] 
forHTTPHeaderField:@"Content-length"];

[request setHTTPBody:[postString 
                      dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] 
 initWithRequest:request delegate:self];

我终于解决了这个问题: 终于,弄明白了哪里出了问题。我正在使用 http://mypath?params=123作为我的网址。我没有演出完整的网址(从不需要其他语言)。但在这里我需要给 htt://mypath/index.php?params=123

最佳答案

我认为你最好使用这样的 NSJSONSerialization 类:

NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                     email, @"Email",
                     fname, @"FirstName",
                     nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];

使用字典然后将其转换为 JSON 比创建它像一个字符串更容易。

祝你好运!

[SWIFT 3.0](更新)

let tmp = ["email": email,
           "FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData

https://stackoverflow.com/questions/9883081/

相关文章:

json - Golang 将 JSON 数组解析成数据结构

python - 使用 JSON 模块进行 pretty-print 时如何实现自定义缩进?

java - 如何在 Java 的 JSON 字符串中找到指定的名称及其值?

python - 使用 simplejson 序列化简单类对象的最简单方法?

json - 在jq中将字符串转换为json

javascript - 短语对象文字表示法中的 "literal"是什么意思?

javascript - 如何使用 Javascript 将数据写入 JSON 文件

ios - 如何在 Swift 中解析 JSON 中的数组?

ios - (Cocoa 错误 3840。)“(字符 0 周围的值无效。)AFNetworking

c# - 强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)