如何将POST请求插入UIWebView

时间:2010-01-04 22:33:53

标签: iphone post

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

      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中。最好的办法是什么?

7 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:10)

谢谢你回答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];

答案 2 :(得分:5)

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

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

这是一大块代码,但很简单,可以放入带有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];
}

答案 3 :(得分:3)

您可以使用类似ASIHTTPRequest的内容来发出POST请求(选择异步执行),然后将响应字符串/数据加载到UIWebView中。请在标题为使用POST或PUT请求发送数据的部分下查看this page,然后查看顶部的创建异步请求部分,了解有关如何使用的信息处理响应字符串/数据。

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

答案 4 :(得分: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加载表单,然后立即提交它,从而向someplace.com执行POST请求(您的URL会有所不同)。结果将显示在WebView中。

表单的具体内容取决于您......

答案 5 :(得分: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];

答案 6 :(得分:0)

这是Swva版本的Seva Alekseyev的答案,对我来说非常合适。谢谢你的好朋友! 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)
}