代码之家  ›  专栏  ›  技术社区  ›  Gazzer

如何在uiwebview中插入post请求

  •  13
  • Gazzer  · 技术社区  · 16 年前

    对于GET请求,我尝试了以下简单方法:

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

    (尽管如果请求包含高UTF-8字符,它似乎不起作用。)

    我想从iPhone上发一篇帖子。

    这也为 sending POST/GET requests 尽管我真正想做的是将生成的网页嵌入到uiwebview中。最好的方法是什么?

    7 回复  |  直到 9 年前
        1
  •  13
  •   Ben Gottlieb    16 年前

    可以使用nsmutableurlrequest,将http方法设置为post,然后使用-loadrequest将其加载到uiwebview中。

        2
  •  10
  •   Louis de Decker    15 年前

    谢谢你回答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:@"<html><body onload=\"document.forms[0].submit()\">"
         "<form method=\"post\" action=\"%@\">", 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:@"<input type=\"hidden\" name=\"%@\" value=\"%@\" >\n", [params objectAtIndex:i*2], [params objectAtIndex:(i*2)+1]]];
        }    
        [s appendString: @"</input></form></body></html>"];
        //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
  •  5
  •   bladnman    13 年前

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

    我只是想加入我的请求版本。我用字典来表示post参数。

    这是一段代码,但非常简单,可以放到一个带有WebView的视图中,并用于所有URL加载。只有当你发送一个“PostDictionary”时,它才会发布。否则,它将使用您发送的URL来获取信息。

    - (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];
    }
    
        4
  •  3
  •   Jorge Israel Peña    16 年前

    你可以用类似的东西 ASIHTTPRequest 提出邮寄请求( 可以选择异步执行 )然后将响应字符串/数据加载到uiWebView中。看 this page 在标题为 通过POST或PUT请求发送数据 然后看看 创建异步请求 顶部的部分,获取有关如何处理响应字符串/数据的信息。

    希望有帮助,如果我误解了你的问题,对不起。

        5
  •  2
  •   Seva Alekseyev    9 年前

    使用loadHTMLString,将一个页面提供给具有隐藏的预填充表单的uiWebView,然后使该页面在加载时执行javascript表单[0].submit()。

    编辑:首先,您将输入收集到变量中。然后您可以这样编写HTML:

    NSMutableString *s = [NSMutableString stringWithCapacity:0];
    [s appendString: @"<html><body onload=\"document.forms[0].submit()\">"
     "<form method=\"post\" action=\"http://someplace.com/\">"
     "<input type=\"hidden\" name=\"param1\">"];
    [s appendString: Param1Value]; //It's your variable
    [s appendString: @"</input></form></body></html>"];
    

    然后将其添加到Web视图:

    [myWebView loadHTMLString:s baseURL:nil];
    

    它将使WebView加载表单,然后立即提交表单,从而向someplace.com执行post请求(您的URL将有所不同)。结果将显示在Web视图中。

    表格的细节由你决定…

        6
  •  0
  •   Dixit Patel    9 年前

    创建post-urlrequest并使用它填充webview

     NSURL *url = [NSURL URLWithString: @"http://your_url.com"];
     NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"];
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
     [request setHTTPMethod: @"POST"];
     [request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
     [webView loadRequest: request];
    
        7
  •  0
  •   onCompletion    9 年前

    这是塞瓦阿列克塞耶夫的答案的快速版本,对我来说非常有效。谢谢你的好同事!以下代码在SWIFT 3.1中。

    fileprivate func prepareDataAndSubmitForRepayment(parameters paramData: [String: Any]) {
        var stringObj = String()
        stringObj.append("<html><head></head>")
        stringObj.append("<body onload=\"payment_form.submit()\">")
        stringObj.append("<form id=\"payment_form\" action=\"\(urlString)\" method=\"post\">") //urlString is your server api string!
    
        for object in paramData { //Extracting the parameters for request
          stringObj.append("<input name=\"\(object.key)\" type=\"hidden\" value=\"\(object.value)\">")
        }
    
        stringObj.append("</form></body></html>")
        debugPrint(stringObj)
        webviewToLoadPage?.loadHTMLString(stringObj, baseURL: nil)
    }