【发布时间】:2019-02-22 03:30:13
【问题描述】:
我正在尝试使用带有正文的 alamofire 发出发布请求,但我一直收到此错误代码“消息:发生错误。” 我在 obj-c 和 afnetworking 中运行相同的 api,一切正常。我是不是用了错误的方法来制作参数?
let parameters: [String: Any] = ["ID": "aaaa@test.com", "PW": "12345", "LoginType": "IDPW", "PushKey": "ios"]
Alamofire.request(loginApi, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
}
我使用 Objective-C 和函数发送的正文
NSDictionary *parameters = @{
@"LoginType": @"IDPW",
@"ID": @"aaaa@test.com",
@"PW": @"12345",
@"PushKey": @"ios"
};
- (void) AsyncHttpRequestWithMethod:(NSString * _Nonnull)method
URLString:(NSString * _Nonnull)URLString
parameters:(NSDictionary * _Nullable)parameters
headers:(NSDictionary * _Nullable)headers
uploadProgress:(nullable void (^)(NSProgress * _Nullable uploadProgress)) uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress * _Nullable downloadProgress)) downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse * _Nullable response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFHTTPRequestSerializer serializer] requestWithMethod:method URLString:URLString parameters:parameters error:nil];
req.timeoutInterval = intTimeInterval;
if (headers && headers.count > 0) {
NSArray *keys = headers.allKeys;
for (int i = 0; i < headers.count; i ++) {
[req addValue:headers[keys[i]] forHTTPHeaderField:keys[i]];
}
}
[[manager dataTaskWithRequest:req uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
if (uploadProgressBlock) uploadProgressBlock(uploadProgress);
} downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
if (downloadProgressBlock) downloadProgressBlock(downloadProgress);
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(@"completionHandler......");
completionHandler(response, responseObject, error);
}] resume];
}
【问题讨论】:
-
您在 Objective-C 中发送的确切 json 正文是什么?
-
我认为您缺少“Content-Type”标头。你在哪里提到过?
-
@Brandon 我在 Objective-C 中发送 nsdictionary。我已经编辑了我的问题
-
@Shruti 我在我的代码中添加标题:HTTPHeaders = ["Content-Type":"application/json"] 仍然无法正常工作