【发布时间】:2015-10-12 13:16:42
【问题描述】:
我正在使用 mycontacts RESTful API 集成到我的应用程序中。现在,我想使用 UITextField 而不是手动输入的用户名和密码。我不知道,如何在 setHTTPBody 中做到这一点。有什么建议吗?
NSURL *URL = [NSURL URLWithString:@"https://api.addressbook.io/v1/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//Here I want to use username and password obtained by UITextField.
[request setHTTPBody:[@"{\n \"username\": \"Enter username\",\n \"password\": \"EnterPassword\",\n \"client\": \"apiary\"\n}" dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response Body:\n%@\n", body);
}];
[task resume];
【问题讨论】: