2010-01-04 31 views
12

對於GET請求,我已經試過這種簡單的方法:如何插入一個POST請求到一個UIWebView

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

(雖然似乎工作不如果請求中含有較高的UTF-8字符)

我想從iPhone發送POST。

這也給出了sending POST/GET requests的概述,但我真正想要做的是將生成的網頁嵌入到UIWebView中。什麼是最好的方法來解決這個問題?

回答

12

您可以使用NSMutableURLRequest,將HTTP方法設置爲POST,然後使用-loadRequest將其加載到您的UIWebView中。

+0

這樣比較好。 – 2010-01-04 23:05:26

+0

這是我嘗試過的(請參閱OP中的鏈接),我嘗試使用connectionDidFinishLoading方法來執行類似[uiWebViewThing loadRequest:responseData]的操作,但它是錯誤的數據類型。響應數據是NSMutable,但它需要NSUrlRequest - 我必須做一些明顯的錯誤。 – Gazzer 2010-01-04 23:17:06

+1

上面的代碼使用NSURLRequest。你需要使用一個NSMutableURLRequest。不要亂用connectionDidFinishLoading,只需使用-loadRequest將其加載到webView中即可。 – 2010-01-04 23:51:12

2

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

然後你把它添加到的WebView:

[myWebView loadHTMLString:s baseURL:nil]; 

這將使的WebView加載窗體,然後立即提交,從而執行一個POST請求到某處.com(你的網址會有所不同)。結果將顯示在WebView中。

形式的具體內容取決於你...

+0

我真的不明白這一點。我試圖根據用戶輸入發送來自iPhone的POST請求,並讓服務器產生一個頁面,這個頁面又會出現在UIWebView內部。 – Gazzer 2010-01-04 22:47:36

+0

對於'WKWebView'(iOS8)也是如此。 因爲也許有錯誤,並且'loadHTMLString'方法可以工作 – Aznix 2014-09-25 10:43:37

3

您可以使用類似ASIHTTPRequest,使POST請求(有了做異步的選項),然後裝入響應字符串/數據進入UIWebView。請在this page下的標題爲的部分發送帶POST或PUT請求的數據,然後查看在頂部創建一個異步請求部分,以獲取有關如何處理響應字符串/數據的信息。

希望有幫助,抱歉,如果我誤解了你的問題。

+0

如何將ASIHttpRequest中的響應字符串加載到UIWebView中? – MikeN 2011-03-19 02:40:37

+0

@MikeN,' - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL' – 2011-04-12 05:58:48

9

謝謝你回答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]; 
+0

這解決了我的問題,非常感謝。 我想改善答案,您可以使用Dictionary而不是Array來避免缺少鍵值對。 使用此示例代碼: 'NSString * hiddenParam = [NSString stringWithFormat:@「 \ n「,鍵,[params objectForKey:key]]; [s appendString:hiddenParam]; }' – krischu 2015-04-29 09:41:56

5

(編輯原來的答案,包括新測試的代碼)

我只是想放棄我的這個請求版本。我用字典來表示發佈參數。

這是一段代碼,但很簡單,可以放入帶有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]; 
} 
0

創建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]; 
0

這裏是塞瓦·阿列克謝耶夫的答案,完全爲我工作的斯威夫特版本。謝謝你的好朋友! BTW下面的代碼在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) 
} 
相關問題