我正在尝试用alamofire和body发帖请求,但我一直有这个错误代码“消息:发生错误。”我在obj-c和afnetworking中运行相同的api,一切正常。我用错误的方法制作参数吗?
let parameters: [String: Any] = ["ID": "[email protected]", "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": @"[email protected]",
@"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];
}
在您的请求中缺少headers
,请使用以下代码获取结果。
let headers = ["Content-Type":"application/json"]
let parameter = ["MemberID": "[email protected]", "MemberPW": "12345", "LoginType": "IDPW", "PushKey": "ios"]
Alamofire.request(loginApi, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: headers)
.responseJSON { (response) in
switch response.result {
case .success:
print("success",response)
case .failure(let error):
print("failure",error)
}
}
你的代码对我来说很好。
没有更多信息,很难确定什么是实际问题。
据我所知,问题是encoding
更改
JSONEncoding.default
与其他可用选项,如URLEncoding.default
让我知道如果它不工作,那么我将删除我的答案