How to send multiple parameterts to PHP server in HTTP post

戏子无情 提交于 2019-11-27 09:37:45

For the network operation these is better supporting API like AFNetworking available witch work async and way better to handle

Tutorials for AFNetworking

Get from here

NSArray *keys = @[@"UserID", ];
NSArray *objects = @[@(userId)];

NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
                            [NSURL URLWithString:BaseURLString]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST"
                                                        path:@"services/UserService.svc/GetUserInfo"
                                                  parameters:parameter];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSError* error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
    if ([jsonObject isKindOfClass:[NSDictionary class]]) {
        // do what ever
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

Given a NSDictionary "params" whose keys and values are strings and where every entry represents one parameter (name/value) you can define a helper category:

@interface NSDictionary (FormURLEncoded)
-(NSData*) dataFormURLEncoded;
@end

dataFormURLEncoded returns a properly encoded character sequence from the given parameters in the dictionary.

The encoding algorithm is specified by w3c: URL-encoded form data / The application/x-www-form-urlencoded encoding algorithm

It can be implemented as follows:

First, a helper function which encodes a parameter name, respectively a parameter value:

static NSString* x_www_form_urlencoded_HTML5(NSString* s)
{
    // http://www.w3.org/html/wg/drafts/html/CR/forms.html#application/x-www-form-urlencoded-encoding-algorithm   , Editor's Draft 24 October 2013
    CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
    CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@~");

    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                             kCFAllocatorDefault,
                                             (__bridge CFStringRef)s,
                                             charactersToLeaveUnescaped,
                                             legalURLCharactersToBeEscaped,
                                             kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

Finally, dataFormURLEncoded composes the character sequence of the encoded parameters. A "parameter" will be composed by concatenating the encoded name, = and encoded value:

parameter := name "=" value

Then, the parameter list will be composed by concatenating the parameters by separating them by a "&":

parameters  := parameter ["&" parameter]

It can be implemented as below:

@implementation NSDictionary (FormURLEncoded)

-(NSData*) dataFormURLEncoded {
    NSMutableData* data = [[NSMutableData alloc] init];
    BOOL first = YES;
    for (NSString* name in self) {
        @autoreleasepool {
            if (!first) {
                [data appendBytes:"&" length:1];
            }
            NSString* value = self[name];
            NSData* encodedName = [x_www_form_urlencoded_HTML5(name) dataUsingEncoding:NSUTF8StringEncoding];
            NSData* encodedValue = [x_www_form_urlencoded_HTML5(value) dataUsingEncoding:NSUTF8StringEncoding];

            [data appendData:encodedName];
            [data appendBytes:"=" length:1];
            [data appendData:encodedValue];
            first = NO;
        }
    }
    return [data copy];
}

@end

Note: The character sequence encodes the strings using Unicode UTF-8.

Example:

Given your parameters:

NSDictionary* params = @{@"a": @"a a", @"b": @"b+b", @"c": @"ü ö"};
NSData* encodedParamData = [params dataFormURLEncoded];

Now, encodedParamData will be added to your body whose content type is application/x-www-form-urlencoded.

The encoded parameter string becomes:

a=a+a&b=b%2Bb&c=%C3%BC+%C3%B6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!