【发布时间】:2014-03-30 14:43:19
【问题描述】:
后端开发人员在 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,所以无法帮助我。
我错过了什么?
【问题讨论】:
-
在某些情况下,我遇到了与 JSON 参数的 ORDER 相关的问题。由于 NSDictionary 是无序的,因此当您将其转换为 JSON 时,参数的顺序可能与您在声明它时使用的顺序不同。尝试手动设置 JSON 字符串并检查它是否有效。如果问题是这个,就得使用有序字典(在GitHub上搜索,有很多实现)
标签: ios iphone json httprequest