2

我正在尝试使用 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];
4

1 回答 1

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"];
于 2013-10-10T17:50:51.493 回答