我正在阅读《 Java Programming Interviews Exposed》一书。他们提供了此代码示例,我不理解:
@Test
public void makeBareHttpRequest() throws IOException {
final URL url = new URL("http", "en.wikipedia.org", "/");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
final InputStream responseInputStream = connection.getInputStream();
final int responseCode = connection.getResponseCode();
final String response = IOUtils.toString(responseInputStream);
responseInputStream.close();
assertEquals(200, responseCode);
System.out.printf("Response received: [%s]%n", response);
}
关于何时需要强制转换变量(在右侧)是否有一些通用规则?为什么将HttpURLConnection强制转换为右侧:
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
但responseInputStream不需要在此处强制转换为右侧:
final InputStream responseInputStream = connection.getInputStream();
Java程序员如何知道何时进行这种类型的转换,何时不进行这种类型的转换?
在此程序中,您HttpURLConnection
之所以会陷入困境,是因为您需要使用该方法HttpURLConnection
,该方法在该方法的父类中可用,但在其父类中不可用setRequestMethod()
。
您可以执行此操作,因为您知道您的URL是HTTP URL,因此URLConnection
将从其返回的对象将是HttpURLConnection
。
您无需转换的结果,connection.getInputStream()
因为它返回InputStream
并且您不需要任何未在中定义的方法InputStream
。
通常,您使用提供所需操作的类-如果您知道将得到的结果强制转换为该类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句