当前位置:  开发笔记 > 编程语言 > 正文

如何将POST请求插入UIWebView

如何解决《如何将POST请求插入UIWebView》经验,为你挑选了3个好方法。

对于GET请求,我尝试过这个简单的方法:

      NSString *urlAddress = @"http://example.com/";
      NSURL *url = [NSURL URLWithString:urlAddress];
      NSURLRequest *request = [NSURLRequest requestWithURL:url];
      [uiWebViewThingy loadRequest:request];

(虽然如果请求包含高UTF-8字符似乎不起作用.)

我想从iPhone发送一个POST.

这也给出了发送POST/GET请求的概述,尽管我真正想做的是将生成的网页嵌入到UIWebView中.最好的方法是什么?



1> Ben Gottlieb..:

您可以使用NSMutableURLRequest,将HTTP方法设置为POST,然后使用-loadRequest将其加载到UIWebView中.



2> Louis de Dec..:

谢谢你回答Seva.我已经用你的代码制作了一个方法,希望这有助于其他人:)

//-------------------------------------------------------------------
//  UIWebViewWithPost
//       init a UIWebview With some post parameters
//-------------------------------------------------------------------
- (void)UIWebViewWithPost:(UIWebView *)uiWebView url:(NSString *)url params:(NSMutableArray *)params
{
    NSMutableString *s = [NSMutableString stringWithCapacity:0];
    [s appendString: [NSString stringWithFormat:@""
     "
", url]]; if([params count] % 2 == 1) { NSLog(@"UIWebViewWithPost error: params don't seem right"); return; } for (int i=0; i < [params count] / 2; i++) { [s appendString: [NSString stringWithFormat:@"\n", [params objectAtIndex:i*2], [params objectAtIndex:(i*2)+1]]]; } [s appendString: @"
"]; //NSLog(@"%@", s); [uiWebView loadHTMLString:s baseURL:nil]; }

使用它

NSMutableArray *webViewParams = [NSMutableArray arrayWithObjects:
                                 @"paramName1", @"paramValue1",
                                 @"paramName2", @"paramValue2",
                                 @"paramName3", @"paramValue3", 
                                 nil];
[self UIWebViewWithPost:self.webView url:@"http://www.yourdomain.com" params:webViewParams];



3> bladnman..:

(编辑原始答案,包括新测试的代码)

我只是想放弃我的这个请求的版本.我用字典来表示帖子参数.

它是一大块代码,但很简单,可以放入带有webview的视图,并用于所有URL加载.如果您发送"postDictionary",它将只发布POST.否则它将使用你发送它的网址来获取东西.

- (void) loadWebView:(UIWebView *)theWebView withURLString:(NSString *)urlString andPostDictionaryOrNil:(NSDictionary *)postDictionary {
    NSURL *url                          = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request        = [NSMutableURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringCacheData
                                         timeoutInterval:60.0];


    // DATA TO POST
    if(postDictionary) {
        NSString *postString                = [self getFormDataString:postDictionary];
        NSData *postData                    = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSString *postLength                = [NSString stringWithFormat:@"%d", [postData length]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
    }

    [theWebView loadRequest:request];
}
- (NSString *)getFormDataString:(NSDictionary*)dictionary {
    if( ! dictionary) {
        return nil;
    }
    NSArray* keys                               = [dictionary allKeys];
    NSMutableString* resultString               = [[NSMutableString alloc] init];
    for (int i = 0; i < [keys count]; i++)  {
        NSString *key                           = [NSString stringWithFormat:@"%@", [keys objectAtIndex: i]];
        NSString *value                         = [NSString stringWithFormat:@"%@", [dictionary valueForKey: [keys objectAtIndex: i]]];

        NSString *encodedKey                    = [self escapeString:key];
        NSString *encodedValue                  = [self escapeString:value];

        NSString *kvPair                        = [NSString stringWithFormat:@"%@=%@", encodedKey, encodedValue];
        if(i > 0) {
            [resultString appendString:@"&"];
        }
        [resultString appendString:kvPair];
    }
    return resultString;
}
- (NSString *)escapeString:(NSString *)string {
    if(string == nil || [string isEqualToString:@""]) {
        return @"";
    }
    NSString *outString     = [NSString stringWithString:string];
    outString                   = [outString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // BUG IN stringByAddingPercentEscapesUsingEncoding
    // WE NEED TO DO several OURSELVES
    outString                   = [self replace:outString lookFor:@"&" replaceWith:@"%26"];
    outString                   = [self replace:outString lookFor:@"?" replaceWith:@"%3F"];
    outString                   = [self replace:outString lookFor:@"=" replaceWith:@"%3D"];
    outString                   = [self replace:outString lookFor:@"+" replaceWith:@"%2B"];
    outString                   = [self replace:outString lookFor:@";" replaceWith:@"%3B"];

    return outString;
}
- (NSString *)replace:(NSString *)originalString lookFor:(NSString *)find replaceWith:(NSString *)replaceWith {
    if ( ! originalString || ! find) {
        return originalString;
    }

    if( ! replaceWith) {
        replaceWith                 = @"";
    }

    NSMutableString *mstring        = [NSMutableString stringWithString:originalString];
    NSRange wholeShebang            = NSMakeRange(0, [originalString length]);

    [mstring replaceOccurrencesOfString: find
                             withString: replaceWith
                                options: 0
                                  range: wholeShebang];

    return [NSString stringWithString: mstring];
}

推荐阅读
echo7111436
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有