我已经尝试了很多次,但是我无法对远程API执行简单的POST请求。我需要发布用户名和密码才能获得登录授权。以下是代码:
imageView.image = UIImage(named : "YourImage")
我做了另一个版本,使用NSDictionary和Json解析(API使用json)
NSURL * url = [NSURL URLWithString:@"http://thapi.xyz/auth/login"];
NSString *postData = @"username=emailExample@gmail.com&password=123456";
NSData * dataBody = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:@"%d",[dataBody length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-unlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:@"Content-Lenght"];
[request setHTTPBody:dataBody];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@" ERROR %@, RESPONSE %@ AND DATA %@",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
这是两个代码的结果:
NSDictionary * login = @{@"username":@"exampleMail@gmail",@"password":@"123456"};
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:login options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLenght = [NSString stringWithFormat:@"%d",[jsonData length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-unlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:@"Content-Lenght"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@" ERROR %@, RESPONSE %@ AND DATA %@",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
我非常感谢所有的答案,对不起我糟糕的英语......
答案 0 :(得分:1)
可能是标题变量的拼写错误(“Content-Lenght”拼写错误):
[request setValue:postLenght forHTTPHeaderField:@"Content-Length"];
答案 1 :(得分:0)
不推荐使用NSURLConnection。请使用nsurlsession尝试此代码....
//replace the following code with your request params
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *clientSessionId = [prefs stringForKey:@"clientSession"];
NSString *bodyString = [NSString stringWithFormat:@"[\"%@\",{\"session_token\":\"%@\",\"request\":[\"GetUnitDetails\",{}]}]",clientSessionId,clientSessionId];
//Make mutable url request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[Settings getMobileUrl]]];
NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
//Change the http method as per your own choice
[request setHTTPMethod:@"POST"];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *connectionError)
{
if ([data length] > 0 && connectionError == nil)
{
NSError *localError = nil;
self.parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
NSString* unitResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [unitResponse dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
}else {
NSLog(@"No response received");
}
}]resume];
答案 2 :(得分:0)
您可以尝试使用NSDictionary
作为参数。以下内容将正确地将参数发送到JSON服务器。
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"http://thapi.xyz/auth/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *login = [[NSDictionary alloc] initWithObjectsAndKeys: @"username":@"exampleMail@gmail",@"password":@"123456",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:login options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
希望这项工作正常......:)
答案 3 :(得分:0)
还要尝试纠正“setValue:postLenght”,因为我猜这不存在,并且可能会将Content-Length设置为0。