后端开发人员在POST请求中给出了以下指示:
- 路由:{url}/{app_name/{controller}/{action}
- 控制器和操作应该是小写字母。
- API测试链接:http:****************
- 请求应该使用POST方法。
- 参数应该通过请求内容主体(FormUrlEncodedContent)传递。
- 参数应该是json格式。
- 参数区分大小写。
由于我没有经验处理第5个协议,所以我进行了搜索并最终完成了我的代码。
-(id)initWithURLString:(NSString *)URLString withHTTPMEthod:(NSString *)method withHTTPBody:(NSDictionary *)body {
_URLString = URLString;
HTTPMethod = method;
HTTPBody = body;
//set error message
errorMessage = @"Can't connect to server at this moment. Try again later";
errorTitle = @"Connection Error";
return self;
}
-(void)fireConnectionRequest {
NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
[mainQueue setMaxConcurrentOperationCount:5];
NSError *error = Nil;
NSURL *url = [NSURL URLWithString:_URLString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *sendData = [NSJSONSerialization dataWithJSONObject:HTTPBody options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody: sendData];
[NSURLConnection connectionWithRequest:request delegate:self];
NSString *jsonString = [[NSString alloc]initWithData:sendData encoding:NSUTF8StringEncoding];
//fire URL connectiion request
[NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) {
//get the return message and transform to dictionary
NSString *data = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
returnMessage = [NSJSONSerialization JSONObjectWithData: [data dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error:&error];
//check return message
if (!error) {
[delegate returnMessageForTag:self.tag];
}
else {
[delegate returnErrorMessageForTag:self.tag];
}
}];
}
我传递了一个格式化为JSON的字典。他同意我能够传递正确的数据。而且我能够连接到API,但是每当我尝试发送注册数据时,它总是返回“FAILED”。连接没有问题,但我无法传输数据。
这里使用相同API的Android开发人员没有任何问题,但由于不熟悉iOS,他无法帮助我解决问题。
我错过了什么?