在目标c中发送HTTP请求

-1 iphone objective-c

我需要连接到服务器而不输入"http://".我只需要从用户那里获得服务器名称和端口号.有了这个,我应该能够连接到特定的服务器......

Mor*_*ast 5

在最简单的形式,它看起来像这样:

- (void)loadHostName:(NSString *)hostName onPort:(NSInteger)portNumber {

    responseData = [[NSMutableData alloc] init];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i", hostName, portNumber]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Oh noes! %@", [error localizedDescription]);
    [responseData release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    // Do something with the data, like load it in a web view.
    [webView loadData:responseData MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:nil];
    [responseData release];
}
Run Code Online (Sandbox Code Playgroud)

在生产代码中,您应该处理缓存请求,身份验证挑战等(请参阅NSURLConnection上的消息),但上面的示例将发送HTTP请求并将其加载到Web视图中.