我无法找到有关此主题的信息。请帮帮我。
我需要通过POST或GET方法将参数传递给我的网络服务器并获得回复。
基本上,如果使用GET方法,我想做 server.com/?user=john&password=smith 之类的操作,并接收动态生成的HTML代码,这些代码是用我的完成的php 脚本。所有这一切都没有使用我的应用程序上的Web浏览器。
通常如何做?
答案 0 :(得分:1)
您需要查看NSMutableURLRequest
和NSURLConnection
。
例如,您可以像这样对您的服务器使用GET请求:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// GET
NSString *serverURL = [NSString stringWithFormat:@"http://yourserver.com/login.php?user=%@&pass=%@", username, password];
NSURL *url = [NSURL URLWithString:serverURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
这将使用包含用户名和密码的查询字符串向服务器发送异步GET请求。
如果您想使用POST请求发送用户名和密码,该方法将如下所示:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// POST
NSString *myRequestString = [NSString stringWithFormat:@"user=%@&pass=%@",username,password];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSURL *url = [NSURL URLWithString:@"http://yourserver.com/login.php"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod: @"POST"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[req setHTTPBody: myRequestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
为了从服务器获取响应,您需要实现NSURLConnection
委托方法,例如:
#pragma mark -
#pragma mark NSURLConnection delegate methods
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// Called if you have an .htaccess auth. on server
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:@"your_username" password:@"your_password" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[connectionData setLength: 0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[connectionData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connectionData release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[connectionData bytes]
length:[connectionData length] encoding: NSUTF8StringEncoding];
// This will be your server's HTML response
NSLog(@"response: %@",content);
[content release];
[connectionData release];
}
参考文献:
NSMutableURLRequest Class Reference
NSURLConnection Class Reference
希望这会有所帮助:)
答案 1 :(得分:0)
通常使用 NSURLConnection 来完成。您还可以使用NSString的方法stringWithContentsOfURL。