我試圖做一個iPhone應用程序,將與特定的JIRA服務器進行交互。我有下面的代碼登錄:AFNetworking版本2內容類型錯誤
NSURL *url = [[NSURL alloc] initWithString:@"https://mycompany.atlassian.net/rest/auth/latest/session/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *postString = [NSString stringWithFormat:@"{\"username\":\"%@\",\"password\":\"%@\"}", username, password];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept" ];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"ERROR: %@", error);
}
];
[operation start];
但它給我具有內容類型做了以下錯誤:
ERROR: Error Domain=AFNetworkingErrorDomain Code=-1011
"Request failed: unsupported media type (415)"
UserInfo=0x8cd6540
{
NSErrorFailingURLKey=https://mycompany.atlassian.net/rest/auth/latest/session/,
NSLocalizedDescription=Request failed: unsupported media type (415),
NSUnderlyingError=0x8c72e70
"Request failed: unacceptable content-type: text/html",
我不知道是什麼問題。我發現this question,我認爲這可能是一個類似的問題,但答案說要麼使用AFJSONRequestOperation
類(我不能因爲我使用AFNetworking版本2,它沒有那個類),或者修復它在服務器端(我也不能明顯的原因)。
當我無法修復服務器端,我無法使用AFJSONRequestOperation
時,我該如何解決此錯誤?
很高興您解決了您的問題。順便說一句,用'stringWithFormat'構建JSON是不可取的(如果密碼中包含某些字符,則會失敗)。最好使用NSDictionary * postDictionary = @ {@「username」:username,@「password」:password};'然後使用NSData * postBody = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];'創建'setHTTPBody'的'NSData'。或者在AF 2.0中使用'POST'和'AFJSONRequestSerializer'(在AF 1.x中使用'AFHTTPClient'和'AFJSONParameterEncoding'的parameterEncoding'),並且它會將字典轉換爲JSON。 – Rob