gpt4 book ai didi

php - 使用变量打开 URL

转载 作者:行者123 更新时间:2023-11-28 19:14:33 25 4
gpt4 key购买 nike

所以我在我使用的服务器上有一个 php 注册脚本。

我如何获取文本框的输入(或与这些框的内容相关的变量/指针),并将它们放入 url 中以注册用户。同样,PHP 和 SQL 数据库都已设置好,我只是在 iOS 中遇到了问题。

示例:

VARIABLE --- PURPOSE
uname username
pass password
name first name
lname last name

现在我需要将其放入这样的 url 中

https://mywebsite/register.php?username=uname&password=pass&firstname=name&lastname=lname&sumbit=submit

该脚本运行良好,我只需要帮助在 iOS 中实现它。

非常感谢。你们真棒!

最佳答案

您可以将 NSURLConnection 与 NSMutableURLRequest 结合使用,如下所示:

//Prepare URL for post
NSURL *url = [NSURL URLWithString: @"https://mywebsite/register.php"];

//Prepare the string for your post (do whatever is necessary)
NSString *postString = [@"username=" stringByAppendingFormat: @"%@&password=%@", uname, pass];

//Prepare data for post
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

//Prepare request object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setTimeoutInterval:20];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

//send post using NSURLConnection
NSURLConnection connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

//Connection should never be nil
NSAssert(connection != nil, @"Failure to create URL connection.");

这(根据您的需要调整 postString)应该向您的服务器异步发送 POST 请求(在您的应用程序的后台),并且服务器上的脚本会运行。

假设你的服务器也在返回一个答案,你可以这样听:
使用 NSURLConnection connection = [[NSURLConnection alloc]initWithRequest:request delegate:self]; 创建连接时,我们告诉连接我们处理服务器在同一个对象中返回的内容,即 self。

当连接返回一个答案时,调用以下三个方法(将它们放在与上面代码相​​同的类中):

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
//Initialize received data object
self.receivedData = [NSMutableData data];
[self.receivedData setLength:0];

//You also might want to check if the HTTP Response is ok (no timeout, etc.)
}

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
[self.receivedData appendData:data];
}

-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(@"Connection failed with err");
}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
//Connection finished loading. Processing the server answer goes here.

}

请记住,您必须处理 https 连接/请求附带的服务器身份验证。要允许任何服务器证书,您可以依赖以下解决方案(尽管这只是推荐用于快速原型(prototype)设计和测试): How to use NSURLConnection to connect with SSL for an untrusted cert?

希望对您有所帮助。

关于php - 使用变量打开 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13217202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com