问题
i have a post request, were i should send a body in the request, but it should be in the form of form-data: the data are now in an nsmutable dictionary as follow :
contacts (
{
Images = (
"http://otrackapi.omegasoftware.ca/ActStaff/public/uploads/user-image-94.jpg"
);
"company_name" = tttt;
"contact_email" = "tttt@me.com";
"contact_fname" = tttt;
"contact_lname" = tttt;
"contact_phone" = 1323223;
lat = "37.330434";
lng = "-122.030163";
remark = Tttt;
"type_id" = 18;
}
)
they should be as form-data as below:
contants[0][contact_name]: bla
contacts[0][comtact_email]:blabla
etc... if you have postman, you can see it its clearer there, any idea how to convert it? thanks
回答1:
I will suggest, try using Alomofire.try to create your JSON and send it to your parameter by a converting it to base64string and tell the Backend guys to decode it then they can get the value.
回答2:
Try below answer,
// your url
NSString *urlString = @"http://www.somesite.com/public/api/v1/create
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];
Now for adding parameters
// api key parameter: here parameter is 'api' its value is 1
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"api_key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"1" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// here parameter is 'subject' and value is taken from '_subjectView.text'
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"subject\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[_subjectView.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// set request body
[request setHTTPBody:body];
// your rest code
like this, you can add multiple parameters with value in the body.
If you want to check boundary in postman see below images,
in postman screen, you may look like this image. In the top right corner, there is one button "Code" click on that button, you will get one pop-up like below image.
check here boundary value.
来源:https://stackoverflow.com/questions/51632724/sending-a-body-in-a-form-of-form-data