iOS上传服务器数据乱码以及报错:NSLocalizedDescription=Request failed: unacceptable content-type: text/plain;

使用的是AFNetworking3.0,只是多封装了一层,以前都是好好的,但是今天POST就郁闷了,我也不知道是后台改了还是怎么,第一次报:content-type: text/plain}

NSErrorFailingURLKey=http://www.138tg.com:8080/smart/user/login, com.alamofire.serialization.response.error.data=<7b227265 73756c74 223a312c 22726561 736f6e22 3a22e6ad a3e7a1ae 5c725c6e 222c2264 61746122 3a7b2265 78706972 6564223a 31343736 33333036 37313737 322c2270 6964223a 22343032 38306438 31353761 32623934 38303135 37613264 30626338 39303030 30222c22 746f6b65 6e223a22 31343736 33323730 37313737 32227d7d>, NSLocalizedDescription=Request failed: unacceptable content-type: text/plain}

查看打印信息很容易发现所以在content-type后面加了个text/plain。

 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain",nil];

然后再次上传:后台说要传json,但是AFN接口里是会转json的,

算了试着手动拼接

    NSString *str = [NSString stringWithFormat:@"{\"%@\":{\"%@\":\"%@\",\"%@\":\"%@\"}}",@"data",@"loginName",@"llj",@"loginPassword",@"123456"];
和字典转json

  NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    dic[@"loginName"] = @"llj";
    dic[@"loginPassword"] = @"123456";
    NSDictionary *parametersDict = @{@"data":dic};
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parametersDict options:0 error:nil];
    NSString *jsonParameters = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
再看又是乱码:

这个问题搞了半天看到了一个哥们同样的问题后得已解决:

[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
原文:帅气的链接


你可能感兴趣的:(Objective-C)