我正在Swift项目中使用CocoaPods实现AFNetworking。我习惯于用Ruby编程,对iOS开发也很陌生。Cocoapods在我的项目中很难正常工作,但我现在可以成功访问AFNetworking库了。
我想做的是用POST点击一个表单,得到一个"text/html"的响应,我可以解析它,这样我就可以判断它是否保存了。这本身不是API,而是由InfusionSoft生成的表单。用户会输入电子邮件地址,我会将其发送到API进行存储。这是我正在使用的代码:
let manager = AFHTTPRequestOperationManager()
var parameters = ["inf_form_xid": "MY_ACCESS_ID",
"inf_form_name": "Webform in Content App",
"infusionsoft_version": "1.34.0.35",
"inf_field_email": self.emailTextField.text]
manager.POST( "https://ns166.infusionsoft.com/app/form/process/REALLYLONGUNIQUEID",
parameters: parameters,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error: " + error.localizedDescription)
})
我收到的错误是来自AFNetworking的回复:
Error: Request failed: unacceptable content-type: text/html
在一天结束时,我想在允许用户继续使用应用程序之前验证它是否由服务器保存。
非常感谢您的帮助。
您必须添加响应所允许的内容类型。
您可以对json内容执行此操作:
manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json")
编辑
如果您使用的是AFNetworking 2.0,请访问AFNetworking wiki:
"默认情况下,AFHTTPRequestOperationManager和AFHTTPSessionManager具有JSON序列化程序。"
因此,您可能应该尝试更改管理器中的响应序列化程序,如下所示:
manager.responseSerializer = AFHTTPResponseSerializer()
这意味着您的服务器正在发送"text/html",而不是已经支持的类型。您可以将可接受的内容类型添加为"text/html",也可以确保从服务器端正确发送json格式。默认情况下,afnetworking的内容类型是objectivec中的json。不知道swift。参考:请求失败:不可接受的内容类型:text.html使用AFNetworking 2.0
我不确定swift,但在目标c中,在搜索答案后,我发现了对我来说非常有效的解决方案。以下是代码片段:
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;