简体   繁体   English

AFNetworking版本2内容类型错误

[英]AFNetworking version 2 content-type error

I'm attempting to make an iphone app that will interact with a particular JIRA server. 我正在尝试制作一个与特定JIRA服务器交互的iPhone应用程序。 I've got the following code to log in: 我有以下代码登录:

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];

But it's giving me the following error having to do with Content-Type: 但它给了我以下与Content-Type有关的错误:

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", 

I'm not sure what the problem is. 我不确定问题是什么。 I found this question , which I thought might be a similar problem, but the answers say to either use the AFJSONRequestOperation class (which I can't because I'm using AFNetworking version 2, which doesn't have that class), or to fix it on the server side (which I also can't for obvious reasons). 我发现这个问题 ,我认为这可能是一个类似的问题,但答案是要么使用AFJSONRequestOperation类(我不能,因为我使用AFNetworking版本2,没有那个类),或者修复它在服务器端(我也不能出于显而易见的原因)。

What can I fix this error when I can't fix the server side and I can't use AFJSONRequestOperation ? 当我无法修复服务器端而无法使用AFJSONRequestOperation时,我可以修复此错误?

If using AFNetworking 2.0, you can use the POST method, which simplifies this a bit: 如果使用AFNetworking 2.0,您可以使用POST方法,这简化了这一点:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = @{@"username":username, @"password":password};
[manager POST:@"https://mycompany.atlassian.net/rest/auth/latest/session/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

This does the creation of the request, setting its Content-Type according to the requestSerializer setting, and encodes the JSON for you. 这会创建请求,根据requestSerializer设置设置其Content-Type ,并为您编码JSON。 One of the advantages of AFNetworking is that you can get out of the weeds of constructing and configuring NSURLRequest objects manually. AFNetworking的一个优点是您可以摆脱手动构建和配置NSURLRequest对象的杂草。


By the way, the "Request failed: unacceptable content-type: text/html" error means that regardless of what you were expecting to receive (eg JSON), you received HTML response. 顺便说一句,“请求失败:不可接受的内容类型:text / html”错误意味着无论您期望接收什么(例如JSON),您都会收到HTML响应。 This is very common: Many server errors (eg the server informing you that the request was malformed, etc.) generate HTML error messages. 这很常见:许多服务器错误(例如服务器通知您请求格式错误等)会生成HTML错误消息。 If you want to see that HTML, in your failure block, simply log the operation.responseString . 如果要在failure块中看到该HTML,只需记录operation.responseString

It turns out the problem is that this one line: 原来问题是这一行:

[request setValue:@"application/json" forHTTPHeaderField:@"Accept" ];

Should be 应该

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type" ];

The error is now solved. 现在解决了错误。 ( Edit : I should have both, see CouchDeveloper's comment.) 编辑 :我应该两者都有,请参阅CouchDeveloper的评论。)

EDIT 编辑
Rob's solution is better, so I'm going with it. Rob的解决方案更好,所以我会继续使用它。 I had actually tried a similar solution to what he shows, but where he had the line, 我实际上尝试过类似于他所展示的解决方案,但他在哪里有线,

manager.requestSerializer = [AFJSONRequestSerializer serializer];

I had the line: 我有这条线:

[manager.requestSerializer
    setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

...which didn't work. ......哪些不起作用。 Kudos to Rob for getting it to work! 感谢Rob让它发挥作用!

I had the same problem in AFNetworking 2.0 and the solution was that I had to make sure I set the AFHTTPRequestSerializer type (In case your request is JSON) the it should be like this. 我在AFNetworking 2.0中遇到了同样的问题,解决方法是我必须确保设置AFHTTPRequestSerializer类型(如果你的请求是JSON)它应该是这样的。

AFHTTPSessionManager *myHTTPManager = ...
[myManager setRequestSerializer:[AFJSONRequestSerializer serializer]];

You have to set both AFHTTPResponseSerializer and AFHTTPRequestSerializer 您必须同时设置AFHTTPResponseSerializerAFHTTPRequestSerializer

if you are using default written class AFAppDotNetAPIClient and you face this error. 如果您使用默认的写作类AFAppDotNetAPIClient并且您遇到此错误。 Must add responseSerializer . 必须添加responseSerializer see your shared method should look like - 看你的共享方法应该是这样的 -

+ (instancetype)sharedClient {

static AFAppDotNetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{
    _sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
    _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    _sharedClient.responseSerializer = [AFHTTPResponseSerializer serializer];
});
return _sharedClient;}

使用这行代码。

operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM