I am trying to a restful web service in iOS application using NSUrlConnection. I am using below code to format the json string and then send over to a restful web service. But I am getting '415(unsupported media type)' response in connectionReceiveResponse: method. Please tell me where I am going wrong here.
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];
You receive HTTP status code 415 when the Content-Type you sent with the request is not a support type. Looking at the code, you are incorrectly setting the Content-Type header. This line:
[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"contentType"];
should be
[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.