please use below code.
+(void)callapi:(NSString *)str withBlock:(dictionary)block{
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@“%@/url”,WebserviceUrl]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:120.0];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (!data) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:@"%@",AMLocalizedString(SomethingWentWrong, nil)] forKey:@"error"];
block(dict);
return ;
}
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//////NSLog(@"%@",dict);
if (!dict) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:AMLocalizedString(ServerResponceError, nil) forKey:@"error"];
block(dict);
return ;
}
block(dict);
}];
}
感谢您的回复。作为后续工作,如果我编写使用用户名和密码登录网站的应用程序,我将如何访问通常由于输入数据而显示的页面数据(即主页面,而不是登录页面)?这与使用NSURLRequest建立NSURLConnection然后下载数据一样简单吗? – achiral
有几种方法。您可以将信息放在[NSURLCredentialStorage](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLCredentialStorage_Class/Reference/Reference.html)中,并将其作为URL,或者使用NSURLConnection委托方法'connection:didReceiveAuthenticationChallenge:'。我强烈建议您查看[URL加载系统编程指南](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/) 10000165i)。 – jtbandes