我试图用表单数据对api做一个简单的POST请求,但作为回报,我总是得到一个状态401。
我可以轻松地在xcode之外(例如Postman )成功地进行调用,我所做的就是将类型数据的键值对发送到url,但在xcode中,它总是失败的。
这是我的AFHTTPClient:
@implementation UnpaktAPIClient
+ (id)sharedInstance {
static UnpaktAPIClient *__sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__sharedInstance = [[UnpaktAPIClient alloc] initWithBaseURL:[NSURL URLWithString:UnpaktAPIBaseURLString]];
});
return __sharedInstance;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (self) {
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setParameterEncoding:AFFormURLParameterEncoding];
}
return self;
}
- (NSDictionary *)login:(NSDictionary *)credentials {
[[UnpaktAPIClient sharedInstance] postPath:@"/api/v1/users/login"
parameters:credentials
success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"%@", error);
}];
return nil;
}我还尝试使用requestOperation创建请求:
- (NSDictionary *)login:(NSDictionary *)credentials {
NSMutableURLRequest *request = [[UnpaktAPIClient sharedInstance] requestWithMethod:@"POST" path:@"/api/v1/users/login" parameters:credentials];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
NSLog(@"success");
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json){
NSLog(@"%@", error);
}];
[operation start];
return nil;
}但我总是得到相同的错误:Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401"。我期待着JSON的反馈,您可以在附图中看到成功的条件。我怀疑这是非常简单的事情,但我正在努力寻找它,我对网络很陌生。任何帮助都会很棒的,谢谢。

更新
因为邮递员的请求有空的平行线和标题,我想我需要进入表单的主体。将请求改为:
- (NSDictionary *)login:(NSDictionary *)credentials {
NSURLRequest *request = [self multipartFormRequestWithMethod:@"POST"
path:@"/api/v1/users/login"
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
NSLog(@"success");
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id json) {
NSLog(@"%@", error);
}];
[operation start];
return nil;
}现在给我一个404错误,如果没有有效的电子邮件和密码,这就是我所期望的,我只需要知道如何将一个添加到表单的正文中,我想添加的任何东西都会给我“请求体流耗尽”的错误。
发布于 2013-01-24 19:44:23
明白了,为表单数据添加键/值对有点冗长,但我这样做了:
NSMutableData *email = [[NSMutableData alloc] init];
NSMutableData *password = [[NSMutableData alloc] init];
[email appendData:[[NSString stringWithFormat:@"paul+100@test.com"] dataUsingEncoding:NSUTF8StringEncoding]];
[password appendData:[[NSString stringWithFormat:@"qwerty"] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendPartWithFormData:email name:@"email"];
[formData appendPartWithFormData:password name:@"password"];https://stackoverflow.com/questions/14504766
复制相似问题