这是我在REST CONSOLE上测试我的Web服务时的JSON响应
{
"d": "{\"token\":\"45b95300-e1ff-4bc1-b45c-9b87babc4df3\",\"timestamp\":\"09/04/2014 12:40:12 PM\"}"
}
这些是我的日志详细信息:
Server Response :<NSHTTPURLResponse: 0x8ea8b70> { URL: http://dev-jrn.stits.co:777/Authonticate.aspx/authenticate } { status code: 500, headers {
"Content-Length" = 91;
"Content-Type" = "application/json; charset=utf-8";
Date = "Thu, 04 Sep 2014 07:18:30 GMT";
Server = "Microsoft-IIS/7.5";
"X-Powered-By" = "ASP.NET";
jsonerror = true;
} }
我的客户端代码
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.textUserName text],[self.textPassword text]];
NSLog(@"PostData: %@",post);
NSURL *url=[NSURL URLWithString:@"http://dev-jrn.stits.co:777/Authonticate.aspx/authenticate"];
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"username", @"abc",
@"password", @"abc",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json; character=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error){
// NSLog(@"Response code: %ld", (long)[response statusCode]);
if(error || !data){
NSLog(@"Server Error : %@", error);
}
else
{
NSLog(@"Server Response :%@",response);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray* latest = [json objectForKey:@"d"];
NSLog(@"items: %@", latest);//Returning items: (null)
}
}
];
代码工作正常,但我知道我错过了一些东西。请帮助。 提前致谢
答案 0 :(得分:0)
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json; character=utf-8" forHTTPHeaderField:@"Content-Type"];
替换此
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
答案 1 :(得分:0)
而不是
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"username", @"abc",
@"password", @"abc",
nil];
试
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"abc", @"username",
@"dch", @"password",
nil];