在Post方法中传递多个参数

时间:2016-05-06 12:40:59

标签: ios http-post nsurlconnection

我是IOS的新手我需要在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];
    }
}

2 个答案:

答案 0 :(得分:0)

您可以将POST方法Params发送为字典。

创建如下:

对于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作为数据。

希望有所帮助......

答案 1 :(得分:0)

如果要发送更多参数传递所有信息。

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];
        }
        }