How do I insert a POST request into a UIWebView

前端 未结 7 1504
故里飘歌
故里飘歌 2021-02-01 08:50

For a GET request I\'ve tried this simple method:

NSString *urlAddress = @"http://example.com/";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLReq         


        
相关标签:
7条回答
  • 2021-02-01 09:06

    (edited original answer to include newly tested code)

    I just wanted to drop in my version of this request. I have used a dictionary to represent the post parameters.

    It's a chunk of code but is simple enough to drop into a view with a webview and use for all URL loading. It will only POST if you send a "postDictionary". Otherwise it will use the url you sent it to just GET things.

    - (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];
    }
    
    0 讨论(0)
  • 2021-02-01 09:12

    Create POST URLRequest and use it to fill 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];
    
    0 讨论(0)
  • 2021-02-01 09:22

    Thanks for you answer Seva. I've made a method out of your code, hope this helps other people :)

    //-------------------------------------------------------------------
    //  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];
    }
    

    to use it

    NSMutableArray *webViewParams = [NSMutableArray arrayWithObjects:
                                     @"paramName1", @"paramValue1",
                                     @"paramName2", @"paramValue2",
                                     @"paramName3", @"paramValue3", 
                                     nil];
    [self UIWebViewWithPost:self.webView url:@"http://www.yourdomain.com" params:webViewParams];
    
    0 讨论(0)
  • 2021-02-01 09:22

    Here is a Swift version of Seva Alekseyev's answer which worked perfectly for me. Thanks for the nice post mate! BTW following code is in 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)
    }
    
    0 讨论(0)
  • 2021-02-01 09:26

    Using loadHTMLString, feed a page to the UIWebView that has a hidden, pre-populated form, then make that page do a Javascript forms[0].submit() on loading.

    EDIT: First, you collect the input into variables. Then you compose HTML like this:

    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>"];
    

    Then you add it to the WebView:

    [myWebView loadHTMLString:s baseURL:nil];
    

    It will make the WebView load the form, then immediately submit it, thus executing a POST request to someplace.com (your URL will vary). The result will appear in the WebView.

    The specifics of the form are up to you...

    0 讨论(0)
  • 2021-02-01 09:28

    You can use an NSMutableURLRequest, set the HTTP method to POST, and then load it into your UIWebView using -loadRequest.

    0 讨论(0)
提交回复
热议问题