美文网首页
webView发送POST请求方法二

webView发送POST请求方法二

作者: Michael_NO1 | 来源:发表于2017-02-26 17:37 被阅读64次
    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请求方法二

          本文链接:https://www.haomeiwen.com/subject/etzowttx.html