2015-04-05 65 views
0

我正在阅读Java Programming Interviews Exposed这本书。他们提供此代码示例,我不明白:为什么我需要在此Java示例中投射HttpURLConnection?

@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程序员知道什么时候做这种铸造,什么时候不?

回答

0

在这个程序中,你投进去HttpURLConnection,因为你需要使用可用的方法在HttpURLConnection,并没有提供它的父类的方法setRequestMethod()

可以做到这一点,因为你知道你的URL是一个HTTP URL,因此将从其返回的URLConnection对象将是一个HttpURLConnection

您不会投下connection.getInputStream()的结果,因为它返回InputStream并且您不需要任何未在InputStream中定义的方法。

通常,您可以使用该类为您提供所需的操作 - 如果您知道所获得的结果可以转换为该类。

1

A URL可以是任何类型的方案,例如, FTP,HTTP,HTTPS,文件等

所以,如果你打算做,你必须将它转换为HttpURLConnection

见下一行一个HTTP操作,请求方法是被设置:connection.setRequestMethod("GET");这是特定于http请求

您不需要投responseInputStream,因为IOUtils能够与抽象类的InputStream的实例一起工作。

相关问题