webView发送POST请求方法二

NSMutableString *postBody = [NSMutableString string];
    for (NSString *paramKey in self.dict)
    {
        NSString *value = self.dict[paramKey];
        NSString *encodeValue = [value URLEncodedFormStringUsingEncoding:NSUTF8StringEncoding];
        
        NSInteger length = [postBody length];
        NSString *paramFormat = (length == 0 ? @"%@=%@" : @"&%@=%@");
        [postBody appendFormat:paramFormat,paramKey,encodeValue];
    }

    DLog(@"----->body:%@",postBody);
    
    NSData *postData = [postBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
    [self.webView loadRequest:request];

    #import "NSString+XYURLAdditions.h"

    @implementation NSString (XYURLAdditions)

    /** 用于URL参数编码保留元字符串内容(保留特殊字符) */
    - (NSString *)URLEncodedFormStringUsingEncoding:(NSStringEncoding)enc {
        NSString *escapedStringWithSpaces = [self percentEscapedStringWithEncoding:enc additionalCharacters:@"&=+" ignoredCharacters:nil];
        return escapedStringWithSpaces;
    }

    /** 用于URL参数编码(特殊字符) */
    - (NSString *)percentEscapedStringWithEncoding:(NSStringEncoding)enc additionalCharacters:(NSString *)add ignoredCharacters:(NSString *)ignore {
        CFStringEncoding convertedEncoding = CFStringConvertNSStringEncodingToEncoding(enc);
        return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)ignore, (CFStringRef)add, convertedEncoding));
    }

    @end

    @implementation NSString (URLEncode)

    - (NSString *)URLEncodedString {
        NSString *encodedString = (NSString *)
        CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8));
   
        return encodedString;
    }
    @end

你可能感兴趣的:(webView发送POST请求方法二)