开发者

Get default port for scheme?

开发者 https://www.devze.com 2023-04-11 05:02 出处:网络
Is there a way to find out what port number a NSURLRequest will use to satisfy a particular NSURL? Obviousl开发者_StackOverflowy, I could hard code port 80 for http request and port 443 for https req

Is there a way to find out what port number a NSURLRequest will use to satisfy a particular NSURL?

Obviousl开发者_StackOverflowy, I could hard code port 80 for http request and port 443 for https requests. But surely there's a built-in way to get the port number from a URL scheme in Cocoa Touch.

The port method on NSURL only returns a value when the port is specified in the URL. It'll work for http://stackoverflow.com:80, but not the more common http://stackoverflow.com.

The context here is that I'm signing into a web service that's redirecting me(Say, from (http://webservice.invalid/path/to/api to http://webservice2.invalid:2003/path/to/api). All URLs are based on the service's base URL, which I want to update to reflect reality and avoid future redirects.

At the moment, I'm extracting the scheme and host, but hadn't considered that the port might change as well. I don't want to specify the port on future requests if I didn't get a port as part of the redirect.


NSURLRequest has a method called URL which returns an NSURL which has a method called port.

NSURLRequest request = ...;

NSNumber *port = [[request URL] port];
NSLog(@"Port: %d", [port intValue]);

Documentation:

port
Returns the port number of a URL conforming to RFC 1808.

- (NSNumber *)port
Return Value The port number of the URL. If the receiver does not conform to RFC 1808, returns nil.

EDIT:

If the port is not set in the URL and you know the scheme, there is nothing wrong with hardcoding the default port. E.g. http = 80, https = 443, ftp = 21. These ports are defined in the standard and you can just store them in a constant somewhere in your code to avoid magic numbers.


Don't hardcode the ports. Use getservent() instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消