【问题标题】:Xcode WebView not passing POST parametersXcode WebView 不传递 POST 参数
【发布时间】:2012-07-13 16:28:16
【问题描述】:

我需要将一些 post 参数传递给服务器,但 php 得到一个空数组 $_POST 这是我的代码:

 NSString* user=UserNameField.stringValue;
NSString* pass=PasswordField.stringValue;
NSString* ID=IDField.stringValue;

NSURL *url = [NSURL URLWithString:ENTERANCE];
url = [NSURL URLWithString:@"http://sphere-beauty.com/test.php"];


NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString* post=[NSString stringWithFormat:@"uname=%@&passwd=%@&id=%@",user,pass,ID];

[req setHTTPMethod:@"POST"];
[req setHTTPBody: [post dataUsingEncoding:NSUTF8StringEncoding]];



[[browser mainFrame] loadRequest:req];

谁能帮忙?

【问题讨论】:

  • 设置 URL 然后覆盖它有什么意义?
  • 那只是为了测试,看post数据

标签: xcode macos webview httprequest


【解决方案1】:

此代码适用于我,向测试页面发送一个简单的 POST 请求。

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *name=@"Freddy Krueger!";
    NSString *encodedName = [name urlencode];
    NSString *postString = [NSString stringWithFormat:@"name=%@", encodedName];
    NSData *data = [postString dataUsingEncoding:NSASCIIStringEncoding];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://192.168.1.100/www/posttest.php"]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:data];

    [web loadRequest:request];

    // Non-ARC
    // [request release];
}

[name urlencode] 在NSString * 上调用urlencode 类别方法,可在此处找到:How do I URL encode a string

web 显然是我的UIWebView。

您的代码可能会失败,因为您没有对参数进行 URL 编码。

【讨论】:

    【解决方案2】:
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"www.aaa.com"]];
    [request setHTTPMethod:@"POST"];
    NSString *request_body = [NSString stringWithFormat:@"u=aaa&p=aaa"];
    [request setHTTPBody:[request_body dataUsingEncoding:NSASCIIStringEncoding]];
    NSError *error;
    NSURLResponse *response;
    NSData *theData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    

    这就是我通常以同步方式与服务器通信的方式...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-03
      • 2014-11-28
      • 2013-11-04
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      相关资源
      最近更新 更多