iOS:使用NSUrlConnection使用RESTFUL Web服务时出现415(不支持的媒体类型)错误

时间:2013-10-10 17:41:04

标签: ios rest

我正在尝试使用NSUrlConnection在iOS应用程序中提供一个安静的Web服务。我使用下面的代码来格式化json字符串,然后发送到一个宁静的Web服务。但我在connectionReceiveResponse:方法中得到'415(不支持的媒体类型)'响应。请告诉我这里哪里出错了。

NSURL * urlLoginAuthentication = [NSURL URLWithString:@“http://www.loginService/mp/api”];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urlLoginAuthentication];
[request setHTTPMethod:@"POST"];

NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:self.txtUserName.text, self.txtPassWord.text,nil] forKeys:[NSArray arrayWithObjects:@"username",@"password", nil]];

NSLog(@"Dict: %@",jsonDict);

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON String: %@",jsonString);

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"contentType"];

[request setValue:@"json" forHTTPHeaderField:@"dataType"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];
NSLog(@"jsonData: %@",jsonData);

self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

1 个答案:

答案 0 :(得分:7)

当您随请求发送的Content-Type不是支持类型时,您会收到HTTP状态代码415。查看代码,您错误地设置了Content-Type标头。这一行:

[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"contentType"];

应该是

[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];