【问题标题】:Post data in Objective C using Json使用 Json 在 Objective C 中发布数据
【发布时间】:2012-04-10 14:28:41
【问题描述】:

我正在尝试将数据发布到 PHP Web 服务。
我很熟悉在 html 中使用查询 $.post 执行此操作,但我非常难以在目标 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。 两者都成功进行了 Web 服务调用(创建了一个新的用户 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

【问题讨论】:

  • 您的服务器工作正常吗?
  • 是的,非常多。正如我在问题中提到的,我使用 jquery 非常成功地做到了这一点。此外,在这种使用 Objective C 的情况下,服务器使用用户 ID 进行响应,只是不接受我发布的数据。
  • 如果我创建一个像 NSMutableDictionary *parms = [NSMutableDictionary dictionary] 这样的字典; [parms setObject:[email text] forKey:@"Email"]; [parms setObject:[名字文本] forKey:@"FirstName"]; [parms setObject:[姓氏文本] forKey:@"LastName"];有没有办法将其转换为 NSData 并发布它?这会比发布 JSON 字符串更好吗?
  • @Praneeta:请发布您的解决方案作为答案.. 它也与我完美合作 :) 谢谢

标签: objective-c ios json post nsurlconnection


【解决方案1】:

试试这个

NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

【讨论】:

    【解决方案2】:

    我已经运行了你的代码,服务器端收到所有消息。

    POST / HTTP/1.1
    Host: linux-test
    User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
    Content-Length: 44
    Accept: application/json
    Content-Type: application/json
    Accept-Language: en
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
    
    {"Email":"test@test.com","FirstName":"test"}
    

    并且跟随代码,如果jsonRequest有非ASCII字符,[jsonRequest length]就会出错。

    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    

    您可以改用strlen

    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
    

    [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
    

    【讨论】:

    • 好吧,由于某种原因,我的服务器端代码不喜欢我发布的数据,我明天会调查一下。感谢您确认我的代码发布了数据。
    • 如果 JSON 包含非 ASCII 字符,则 [jsonRequest length] 将是错误的。 - 是的,这是一个大问题!感谢您提供的信息-我刚刚花了 2 天时间调试一个错误的请求。从我获取原始 JSOn 的 ipad 上看起来一切都很好,然后使用另一个可以正常工作的客户端发布服务... JSOn 看起来很棒,有使用 wireshark 查看 WS 接收到的实际数据被缩短
    • @looyao 我尝试了您提供的两个选项,但我仍然设置相同的错误。你能帮我一些想法吗?数据我试图发送是{ “prefferedName”: “eivFEGX5pXWBGoqNNtF3og ==”, “nameOnCard”: “eivFEGX5pXWBGoqNNtF3og ==”, “MACID”: “M2 / ZIJ5pUB37EnF3tmvdtOnozUeOk + iAM82i2Z0nDEFVsc69vqUXNltN6R2dj7nz”, “expiryDateMonth”: “XAcdf3HTEn3pb2TlWQKHHA ==” ,"appVersion":"e6NpxcXU34gHeOyowJbWFQ==","cardNumber":"7qYGPbnqgAMwMJ2GoCEGF4neQanULztzvblT873xj4o="}
    【解决方案3】:

    我认为你最好使用这样的 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
    

    【讨论】:

    • 谢谢,找出问题所在。我使用mypath?params=123 作为我的网址。我没有演出完整的网址(从不需要其他语言)。但在这里我需要给 htt://mypath/index.php?params=123
    • 谢谢。但是有什么方法可以简单地在复杂的 json 对象中生成“tmp”字典。生成对应的字典很无聊..ex:{"user":{"id":"18888888888","pass":"12345678",...},"animal":{"code":{"id" :1,"code":123456},"key":true}} 生成让我感到无聊的字典。
    • 在添加标题之前无法为我工作:[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    • 感谢您的建议。节省了我很多时间。
    【解决方案4】:
    NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@posts", SeverURL]];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"content-type" value:@"application/json"];
    [request addRequestHeader:@"User-Agent" value:@"iOS"];
    
    request.allowCompressedResponse = NO;
    request.useCookiePersistence = NO;
    request.shouldCompressRequestBody = NO;
    request.delegate=self;
    NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
    [request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
    
    [request startSynchronous];
    

    【讨论】:

    • 我对 JSON 请求有一个类似的问题。我不知道为什么,但添加 User-Agent:iOS 解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多