在Post方法中传递多个参数
问题描述:
我是IOS新手我需要在Post方法中传递多个参数。我在post方法中成功地传递了一个参数,但成功传递了多个参数。 我已经完成的代码:在Post方法中传递多个参数
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSString *post = [NSString stringWithFormat:@"branch_id=%@",str];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if(theConnection){
mutableData = [[NSMutableData alloc]init];
}
}
答
您可以发送POST方法Params作为Dictionary。
创建如下:
对于JSON:
NSMutableDictionary *params = [NSMutableDictionary new];
[params setValue:@"18" forKey:@"branch_id"];
[params setValue:@"OMR" forKey:@"branch_name"];
[params setValue:@"Chennai" forKey:@"branch_city"];
上面给出您可以添加参数。
之后,转换本字典数据,并将其传递给htmlBody方法如下:
NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error];
在此之后,转换
[request setHTTPBody:postData];
对于表格数据:
NSString *params = [NSString stringWithFormat:@"branch_id=%@&branch_name=%@",branch_id,branch_name];
然后像你一样将其转换为数据。之后,将其设置为htmlBody作为数据。
希望它有帮助..
+0
如果你想发布JSON,这很好,但是发布在代码中的代码是一个表单发布。所以张贴JSON是不行的。 – rckoenes
+0
更新了我的答案。 @rckoenes –
答
如果你想发送更多的参数传递所有的信息。
NSString *parameter = [NSString stringWithFormat:@”firstname=%@&lastname=%@”,firstName, lastName]; //Parameter values from user.
NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: @”application/x-www-form-urlencoded; charset=utf-8″ forHTTPHeaderField:@”Content-Type”];
[theRequest setHTTPMethod:@”POST”];
[theRequest setHTTPBody:parameterData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(connection)
{
mutableData = [[NSMutableData alloc] init];
}
}
随着你努力是哪一部分?将参数添加到您的方法或帖子正文? – rckoenes
NSString * post = [NSString stringWithFormat:@“branch_id =%@&type =%@&name =%@”,str,str_name,str_type]; –
我想通过三个参数,其中3参数可以从不同的URL获取,我转换为字符串格式,只有我想作为参数传递给你的代码@BhavinRamani –