如何在iOS应用程序中使用Web服务器?样品

时间:2014-01-15 22:13:40

标签: ios json web ssh request

我写了类似的问题,我回答“如何在iOS应用中使用网络服务器?”但我需要样品,因为对我来说更简单一些样品是如何工作的,例如你可以帮我解决这个样品:

如果我想要/注册新用户,如何在我的服务器上实现请求,我将收到服务器在JSON中的回答,我需要在变量'data'中发送它POST?对于耗尽的服务器是http://myserver.com:8080

{ 
 email:
 password:
}  //this is register form but  how named this field?

我会收到这样的答案:

{
result:[OK|fail]
 message: [error if fail]
 data: [if OK]
}

我需要样本如何发送和接收/注册请求。对不起我的英语,它变得更好:))

更新另外我无法理解如何在Objective-C中使用此表单?

2 个答案:

答案 0 :(得分:0)

所以,在这里你有我的太阳穴发送登录请求,我已经实现了AFNetworking(https://github.com/AFNetworking/AFNetworking)和NSJSONSerialization来解析Json响应。很难给你一个示例代码,但我认为如果你自定义这段代码,一切都应该可以正常工作。

        - (void)sentLoginReqWithLogin:(NSString *)email andPassword:(NSString *)pass {

            NSDictionary *params = @{@"email" : email,
                                     @"password" : pass
                                     };


            AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:HOST_URL]];
            NSMutableURLRequest *request = [httpClient requestWithMethod:POST
                                                                    path:LOGIN_URL
                                                              parameters:params];


            AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
            [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

            [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

                NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
                NSDictionary *response = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:operation.responseData options:kNilOptions error:nil];

    //HERE YOU HAVE A RESPONSE (your server answer)
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {         
                NSLog(@"Error: %@", error);      
            }];


            [operation start];

}

答案 1 :(得分:0)

// Post data to server
NSURL * url = [NSURL URLWithString:@"http://myserver.com/register/"]];

NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
NSString * bodyString = [NSString stringWithFormat:@"&username=%@&password=%ld", "username", "password"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSASCIIStringEncoding]];

NSURLConnection * urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];


// On server, do this (assuming PHP)
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];

// Do w/e checks you need to do against the username and password, be sure to hash and salt the password
// Store user information in database