Programming

요청 실패 : 허용되지 않는 콘텐츠 유형 : AFNetworking 2.0을 사용하는 text / html

procodes 2020. 5. 7. 20:06
반응형

요청 실패 : 허용되지 않는 콘텐츠 유형 : AFNetworking 2.0을 사용하는 text / html


AFNetworking의 새 버전 2.0을 시험 중이며 위의 오류가 발생합니다. 왜 이런 일이 일어나는지 아십니까? 내 코드는 다음과 같습니다.

    NSURL *URL = [NSURL URLWithString:kJSONlink];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [[NSOperationQueue mainQueue] addOperation:op];

Xcode 5.0을 사용하고 있습니다.

또한 오류 메시지는 다음과 같습니다.

Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/html" UserInfo=0xda2e670 {NSErrorFailingURLKey=kJSONlink, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xda35180> { URL: kJSONlink } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 2898;
    "Content-Type" = "text/html";
    Date = "Tue, 01 Oct 2013 10:59:45 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = Apache;
    Vary = "Accept-Encoding";
} }, NSLocalizedDescription=Request failed: unacceptable content-type: text/html}

kJSONlink를 사용하여 JSON을 숨겼습니다. JSON을 반환해야합니다.


이는 "text/html"이미 지원되는 유형 대신 서버가 전송 중임을 의미합니다 . 내 솔루션을 추가하는 것이었다 "text/html"acceptableContentTypes에 세트 AFURLResponseSerialization클래스입니다. "acceptableContentTypes"를 검색 @"text/html"하고 세트에 수동으로 추가하십시오 .

물론 이상적인 해결책은 서버에서 전송 된 유형을 변경하는 것이지만이를 위해서는 서버 팀과 대화해야합니다.


RequestOperationManager응답 시리얼 라이저를 설정 HTTPResponseSerializer하여 문제를 해결했습니다.

목표 -C

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

빠른

manager.responseSerializer = AFHTTPResponseSerializer()

이 변경을하면 acceptableContentTypes모든 요청 에 추가 필요가 없습니다 .


@jaytrixz의 답변 / 댓글을 한 단계 더 발전 시켜서 기존 유형의 세트에 "text / html"을 추가했습니다. 그렇게하면 서버 측에서 "application / json"또는 "text / json"으로 수정하면 완벽하게 작동한다고 주장합니다.

  manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

서버 측에서 다음을 추가했습니다.

header('Content-type: application/json');

내 .php 코드에 추가하면 문제가 해결되었습니다.


다른 관점에서이 문제를 해결했습니다.

서버가 Content-Type: text/html헤더 와 함께 JSON 데이터를 보내면 생각합니다 . 서버 사람이 HTML을 보내려고했지만 실수로 JSON으로 변경되었다는 의미는 아닙니다. 그것은 서버 사람이 Content-Type헤더가 무엇인지 신경 쓰지 않는다는 것을 의미합니다 . 따라서 서버 측이 클라이언트 측으로 신경 쓰지 않으면 Content-Type헤더를 무시하는 것이 좋습니다 . Content-Type헤더 체크인 을 무시하려면AFNetworking

manager.responseSerializer.acceptableContentTypes = nil;

이런 식으로 AFJSONResponseSerializer(기본 설정)은 Content-Type응답 헤더 를 체크인하지 않고 JSON 데이터를 직렬화합니다 .


"텍스트 / 일반"컨텐츠 유형을 수신 할 수있는 간단한 방법 :

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

마찬가지로 "text / html"컨텐츠 유형을 사용하려는 경우 :

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

@Andrie 답변에 따라 아래 줄을 시도했지만 작동하지 않았습니다.

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

그래서 더 많은 사냥을 한 후에, 나는 그것을 성공적으로 작동시키기 위해 일했습니다.

여기 내 코드 조각이 있습니다.

AFHTTPRequestOperationManager *operation = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    AFJSONResponseSerializer *jsonResponseSerializer = [AFJSONResponseSerializer serializer];

    NSMutableSet *jsonAcceptableContentTypes = [NSMutableSet setWithSet:jsonResponseSerializer.acceptableContentTypes];
    [jsonAcceptableContentTypes addObject:@"text/plain"];
    jsonResponseSerializer.acceptableContentTypes = jsonAcceptableContentTypes;
    operation.responseSerializer = jsonResponseSerializer;

Hope this will help someone out there.


This is the only thing that I found to work

-(void) testHTTPS {
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:[NSString stringWithFormat:@"%@", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

If someone is using AFHTTPSessionManager then one can do like this to solve the issue,

I subclassed AFHTTPSessionManager where I'm doing like this,

NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;

In my case, I don't have control over server setting, but I know it's expecting "application/json" for "Content-Type". I did this on the iOS client side:

manager.requestSerializer = [AFJSONRequestSerializer serializer];

refer to AFNetworking version 2 content-type error


Just add this line :

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

I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!

The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes with a Set containing the content type value in question.

The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:

serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>

A good question always have multiple answers, to reduce and help you choose the right answer, here I am adding my own too. I have tested it and it works fine.

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.yourdomain.com/appname/data/ws/index.php/user/login/"]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:@"POST" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"%@", json);
    //Now convert json string to dictionary.
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@", error.localizedDescription);
}];

 UIImage *image = [UIImage imageNamed:@"decline_clicked.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);


NSString *queryStringss = [NSString stringWithFormat:@"http://119.9.77.121/lets_chat/index.php/webservices/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[MBProgressHUD showHUDAddedTo:self.view animated:YES];


[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
 {


     [formData appendPartWithFileData:imageData name:@"fileName" fileName:@"decline_clicked.png" mimeType:@"image/jpeg"];



 }
      success:^(AFHTTPRequestOperation *operation, id responseObject)
 {



    NSDictionary *dict = [responseObject objectForKey:@"Result"];

    NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];


 }
      failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
     NSLog(@"Error: %@ ***** %@", operation.responseString, error);
 }];

참고URL : https://stackoverflow.com/questions/19114623/request-failed-unacceptable-content-type-text-html-using-afnetworking-2-0

반응형