我有一个发布请求,我在该请求中发送了一个正文,我在邮递员上尝试了它,效果很好,如发布的图片所示,我从邮递员那里获取了代码,如下图所示,并将其粘贴到我的xcode项目中,下面是完整代码:
NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
@"x-session": @"48afbfc4c633983555caa8a816a00e966fb22863",
@"cache-control": @"no-cache",
@"postman-token": @"5a2ba3be-42e0-95e3-2866-29f8ce83c32a" };
NSArray *parameters = @[ @{ @"name": @"contacts[0][company_name]", @"value": @"Ali" },
@{ @"name": @"contacts[0][type_id]", @"value": @"5" },
@{ @"name": @"contacts[0][contact_fname]", @"value": @"jaber" },
@{ @"name": @"contacts[0][contact_lname]", @"value": @"jaber2" },
@{ @"name": @"contacts[0][contact_phone]", @"value": @"70034491" },
@{ @"name": @"contacts[0][remark]", @"value": @"sdsdd" },
@{ @"name": @"contacts[0][images][0]", @"value": @"https://otrackapi.omegasoftware.ca/ActStaff/public/uploads/user-image-94.jpg" },
@{ @"name": @"contacts[0][lat]", @"value": @"33.311" },
@{ @"name": @"contacts[0][lng]", @"value": @"33.234" },
@{ @"name": @"contacts[0][contact_email]", @"value": @"me@me.com" } ];
NSString *boundary = @"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSError *error;
NSMutableString *body = [NSMutableString string];
for (NSDictionary *param in parameters) {
[body appendFormat:@"--%@\r\n", boundary];
if (param[@"fileName"]) {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"; filename=\"%@\"\r\n", param[@"name"], param[@"fileName"]];
[body appendFormat:@"Content-Type: %@\r\n\r\n", param[@"contentType"]];
[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];
if (error) {
NSLog(@"%@", error);
}
} else {
[body appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n", param[@"name"]];
[body appendFormat:@"%@", param[@"value"]];
}
}
[body appendFormat:@"\r\n--%@--\r\n", boundary];
NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https:xxxxxxxxxxxxxxxx"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"%@", httpResponse);
}
}];
[dataTask resume];
响应返回以下错误:
response = {
exception = GeneralException;
message = "Undefined index: type_id";
};
在我询问后端人员之后,此错误意味着不包括type_id。 但实际上它是包含在内的,我没有更改邮递员提供的代码。 任何人都可以知道发生了什么事吗?
谢谢
答案 0 :(得分:0)
我认为此错误是因为您在字典中像字符串一样传递5,在数字中像@(5)
一样传递它。