Under what circumstances would one use a HostnameVerifier over a TrustManager in Java?
Never. They do different things. TrustManage authenticates certificates as part of SSL. HostnameVerifier verifies host names as part of HTTPS. They're not in competition.
Is one recommended over the other?
No.
EDIT
- The
TrustManager
runs during the TLS handshake. If it indicates failure, the handshake is aborted and the connect fails. - The
HostnameVerifier
runs after the TLS handshake, over a TLS connection that is already valid from the TLS point of view, so at that point you know that the certificate is valid, signed by a trusted issuer, non-expired (?), etc., and all you have to do is decide (a) whether it's from the correct server and (b) whether you trust that server. You might do (b) inside aTrustManager,
but far more commonly you wouldn't provide your ownTrustManager
at all.