使用命令行向我的API
服务器注册客户端的方法是
curl -d'{"email": "e", "memberExternalId": "m"}' -H"Content-Type: application/json" https://api-myapp.com/register
{"memberId":"78f7f8a4-a8c9-454a-93a8-6633a1076781","clientId":"111322610106743984083443169763434312591","clientSecret":"255682200164339900511209955730378006963"}
我正在尝试使用Objective-C
与AFNetworking
做类似的事情。我当前的代码看起来像
- (void)connectWithServer {
NSLog(@"connecting with server");
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
[manager POST:@"http://api-myapp.com/register"
parameters:@{@"email": @"e", @"memberExternalId": @"m"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
我在控制台中看到的是
2014-11-15 15:13:29.719 myapp-ios[42377:70b] Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0xb61e130 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0xb3071b0> { URL: http://api-myapp.com/register } { status code: 400, headers {
"Accept-Ranges" = none;
Connection = close;
"Content-Length" = 206;
"Content-Type" = "text/html";
Date = "Sat, 15 Nov 2014 23:13:29 GMT";
Server = "WildFly/8";
"X-Powered-By" = "Undertow/1";
} }, NSErrorFailingURLKey=http://api-myapp.com/register, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<636f6d2e 66617374 6572786d 6c2e6a61 636b736f 6e2e636f 72652e4a 736f6e50 61727365 45786365 7074696f 6e3a2055 6e726563 6f676e69 7a656420 746f6b65 6e202765 6d61696c 273a2077 61732065 78706563 74696e67 20282774 72756527 2c202766 616c7365 27206f72 20276e75 6c6c2729 0a206174 205b536f 75726365 3a20696f 2e756e64 6572746f 772e7365 72766c65 742e7370 65632e53 6572766c 6574496e 70757453 74726561 6d496d70 6c403132 66336263 613b206c 696e653a 20312c20 636f6c75 6d6e3a20 375d>, NSUnderlyingError=0xb60f160 "Request failed: unacceptable content-type: text/html"}
我做错了什么?为什么Content-Type
仍为text/html
?
答案 0 :(得分:4)
这正是错误所说的:当您期待JSON时,您的服务器正在为400状态代码发回一个网页(HTML)。
400状态代码用于错误请求,这可能是因为您将URL格式编码的文本发送为application/json
而生成的。您真正想要的是将AFJSONRequestSerializer
用于您的请求序列化程序。
manager.requestSerializer = [AFJSONRequestSerializer serializer];