我正在尝试使用Form-Data向api执行简单的POST请求,但我总是得到状态401作为回报。
我可以很容易地在xcode之外调用(例如在Postman中),我所做的就是使用Form-Data类型的键值对POST到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反馈,您可以在附图中看到成功情况。我怀疑这是非常简单的事情,但我想把它拉出来试图找到它,我对网络很新。任何帮助都会很棒,谢谢。
更新
由于Postman请求有空白的参数和标题,我想我需要进入表单体。将请求更改为:
- (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错误,这是我没有有效的电子邮件和密码所期望的,我只需要弄清楚如何添加一个到表单的主体,我尝试添加的任何东西给我“请求身体流疲惫“错误。
答案 0 :(得分:8)
知道了,事实证明,为形式数据添加键/值对有点冗长,但我完成了这样做:
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"];