2011-06-16 130 views
-1

我需要连接到服务器而不键入“http://”。我只需要获取用户的服务器名称和端口号。有了这个,我应该能够连接到特定服务器...在目标c中发送HTTP请求

回答

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]; 
} 

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

+0

@Richard设置你的ivars到零,当你与完成他们总是做一件好事,但是我把它留在了这个问题上。自动释放它是没有意义的。 – 2011-07-07 08:24:57

+0

根据请求的结果,'connectionData'变量最后一次在'connectionDidFinishLoading:'或'connection:didFailWithError:'中被访问。没有更多的NSURLConnection回调函数,所以没有东西可以再次访问变量,并将它设置为nil不会给你带来任何好处。同样的事情autorelasing它。这只是意味着autorelease池将在稍后发布,而不是你现在这样做。在这两种情况下,你都完成了这个变量,所以你最好尽可能的保持你的内存管理。也不要在'dealloc'中释放它。 – 2011-07-07 12:43:24

+0

你不是在谈论我正在谈论的案例。这不是生产力。删除。 – Richard 2011-07-07 13:24:26

1

试试这个,

NSURL *aUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%i", hostName, portNumber]]; 
NSURLRequest *request = [NSURLRequest requestWithURL:aUrl 
             cachePolicy:NSURLRequestUseProtocolCachePolicy 
            timeoutInterval:60.0]; 


    NSURLResponse *resp = nil; 
    NSError *err = nil; 
    NSData *response = [NSURLConnection sendSynchronousRequest: theRequest    returningResponse: &resp error: &err]; 
NSString * theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
[resp release]; 
[err release]; 
NSLog(@"response: %@", theString); 
+0

同步请求不好,因为: 1.它们阻塞运行循环,所以如果它们在主线程上调用,则在等待响应时UI被锁定。 2.您无法取消同步请求。 3.您无法响应身份验证挑战。 4.您无法验证SSL证书错误。 5. ... 请不要使用同步请求,即使它们需要较少的代码。 – 2011-06-16 07:30:52

0

也可以硬编码HTTP://与服务器名称

例如

NSString *serverName = "stackoverflow.com"; 
NSNumber *portNumber = 10; 
NSString *finalYrl = [NSString StringWithFormat:@"HTTP://%@:%@",serverName , portNumber];