我有一个问题。我从程序(xcode,我在 Objective C 上开发)向服务器发送一个 POST
请求,数据已发送,但我需要在网站上注册(身份验证)并且我不知道我是如何发送这个字符串的
NSString * param = [NSString stringWithFormat:@"action=login&name=%@&password=%@", myName, myPassword]
我的完整代码:
request.HTTPMethod = @"POST";
NSString * myName = _loginLogin.text;
NSString * myPassword= _passwordLogin.text;
NSString * param = [NSString stringWithFormat:@"action=login&name=%@&password=%@", myName, myPassword];
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
我使用这个*(www.dnevnik.ru)*页面。
对于我的网站字符串 NSString *postString = [NSString stringWithFormat:@"&username=%@&password=%@", username, password];
不适合?
最佳答案
使用以下代码: 只需添加
@property (nonatomic, strong) NSMutableData *responseData;
在您的.h文件中
NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults];
NSString *username = [loginData objectForKey:@"username"] ;
NSString *password = [loginData objectForKey:@"password"];
NSString *postString = [NSString stringWithFormat:@"&username=%@&password=%@", username, password];
NSString *urlString = @"http://YourUrl";
NSURL *myURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *detailRequestToServer =[NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[detailRequestToServer setHTTPMethod:@"POST"];
[detailRequestToServer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
const char *utfString = [postString UTF8String];
NSString *utfStringLenString = [NSString stringWithFormat:@"%zu", strlen(utfString)];
[detailRequestToServer setHTTPBody:[NSData dataWithBytes: utfString length:strlen(utfString)]];
[detailRequestToServer setValue:utfStringLenString forHTTPHeaderField:@"Content-Length"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:detailRequestToServer delegate:self];
if (theConnection)
{
self.responseData = [[NSMutableData alloc] init];
}
else
NSLog(@"Connection Failed!");
关于html - 发送数据到网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20120894/