我进入了应用程序开发的最后阶段,这是我以前从未做过的事情。我的朋友使用django rest框架开发了API,并为我的应用发送和接收数据。我需要验证我的应用程序才能连接到它,发送一些数据并接收数据。
到目前为止,我发现的是:
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/my/path/to/api/login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"myUsername", @"myPassword"];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", authData];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// ------------------------------------------------ -------------------------------------------------- ---------------------------------- //
//EDIT: Added this based on answer form @Quver.
NSURLResponse *response1;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response1 error:&responseError];
if (result.length > 0 && responseError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:result
options:0
error:NULL];
NSLog(@"Got response form server: %@", greeting);
}
这等于输出,例如:<0a0a3c68 746d6c3e 0a0a2020 20203c68 6561643e 0a202020 20202020 200a2020 20202020 20200a20 20202020 +约50行类似的东西。希望这可以帮助。
// ------------------------------------------------ -------------------------------------------------- --------------------------------------- //
我想这是创建请求的方法。接下来我该怎么办?而且我怎么知道我已经连接了?然后,如果我已连接,如何获得那里的数据表格?(我有一个将json作为输出的网址-这就是我想要得到的)。假设网址为http://localhost:8080/url/that/gives/json/
。
感谢您的任何帮助。希望这对于问题是足够的信息。我将添加其他要求。
经过几天的搜索,我找到了一种方法。首先,我们需要令牌进行身份验证。我现在通过终端生成它:
curl -X POST -d "grant_type=password&username=<your username>&password=<your password>" http://<client secret>:<client id>@url/to/token/page
然后,在您要连接的视图控制器中:
//always put </> at the end of link
NSURL *aUrl = [NSURL URLWithString: @"http://where/you/trying/to/conect"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:@"<type> <your token>"] forHTTPHeaderField:@"Authorization"];
[request setHTTPMethod:@"GET"];
NSError *error = nil;
self.response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
这将返回页面应返回的所有json。这可能不是最安全的方法,但这正是我现在需要的。稍后,我将介绍更安全的解决方案,例如OAuth 2。
希望这对某人有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句