将JSON数据发布到服务器 [英] Posting JSON data to server

查看:178
本文介绍了将JSON数据发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON数据发布到服务器。
我的JSON是:
{
用户名:样本,
密码:密码-1
}

I am trying to post and JSON data to server. My JSON is: { "username":"sample", "password" : "password-1" }

我将它发送到服务器的方式是:

The way I am sending it to server is:

NSError *错误;

NSError *error;

NSString *data = [NSString stringWithFormat:@"{\"username\":\"%@\",\"password\":\"%@\"}",_textFieldUserName.text,_textFieldPasssword.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSData *jsonData = [NSJSONSerialization JSONObjectWithData:postData options:0 error:&error];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"My URL"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];

NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:requestHandler options:0 error:&error];
NSLog(@"resposne dicionary is %@",responseDictionary);

NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);

创建的JsonData是服务器接受的有效JSON。
但是应用程序崩溃了,错误是:

The JsonData that is created is a valid JSON accepted by the server. But the app is crashing and the error is:

- [__ NSCFDictionary长度]:无法识别的选择器发送到实例0x1702654c0

-[__NSCFDictionary length]: unrecognized selector sent to instance 0x1702654c0

我在这里做错了什么?

推荐答案

我总是在我的应用程序中使用此方法来执行API调用。这是post方法。它是异步的,因此您可以指定在服务器应答时调用的回调。

I always use this method in my apps to perform API calls. This is the post method. It is asynchronous so you can specify a callback to be called when the server answer.

-(void)placePostRequestWithURL:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
    NSString *urlString = [NSString stringWithFormat:@"%@", action];
    NSLog(@"%@", urlString);

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];

    NSString *jsonString;
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

        NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody: requestData];

        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
    }
}

您可以轻松地拨打电话:

You can easily call it:

- (void) login:(NSDictionary *)data
                    calledBy:(id)calledBy
                 withSuccess:(SEL)successCallback
                  andFailure:(SEL)failureCallback{
    [self placePostRequestWithURL:@"yourActionUrl"
                  withData:data
               withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
                   NSString *string = [[NSString alloc] initWithData:rawData
                                                            encoding:NSUTF8StringEncoding];

                   NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                   NSInteger code = [httpResponse statusCode];
                   NSLog(@"%ld", (long)code);

                   if (!(code >= 200 && code < 300)) {
                       NSLog(@"ERROR (%ld): %@", (long)code, string);
                       [calledBy performSelector:failureCallback withObject:string];
                   } else {
                       NSLog(@"OK");

                       NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
                                               string, @"id",
                                               nil];
                       [calledBy performSelector:successCallback withObject:result];
                   }
               }];
}

最后,你调用:

NSDictionary *dataToSend = [NSDictionary dictionaryWithObjectsAndKeys:
_textFieldUserName.text, @"username", 
_textFieldPasssword.text, @"password", nil];

[self login:dataToSend 
    calledBy:self 
    withSuccess:@selector(loginDidEnd:) 
    andFailure:@selector(loginFailure:)];

别忘了定义你的回调:

- (void)loginDidEnd:(id)result{
    NSLog(@"loginDidEnd:");
    // Do your actions
}

- (void)loginFailure:(id)result{
    NSLog(@"loginFailure:");
    // Do your actions
}

这篇关于将JSON数据发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆