我向服务器发送注册消息,如下所示:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
[request setValue:API_KEY forHTTPHeaderField:@"api_key"];
NSString *dataString = [NSString stringWithFormat:@"username=%@&password=%@", username, encryptedPassword];
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
// Connection
NSURLResponse *response = nil;
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Print results
NSLog(@"response: %@", response);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(@"response: %d", [(NSHTTPURLResponse *)response statusCode]);
}
id jsonObject = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&jsonError];
NSLog(@"jsonObject: %@", jsonObject);
连接成功,但我得到了错误响应:
=> response: 400
=> jsonObject: {
error = "Please provide username.USERNAME:";
}
服务器收到一个空用户名,但我确定我将一个有效的用户名传递给http body(转换为NSData)。数据包含以下信息(转换回字符串):
username=cc24@cc.com&password=12345678nW7wMNio0bsNBHGqY7VgSw%3D%3D
我不知道发生了什么。但该API适用于Android应用程序。