Java Reference
In-Depth Information
Listing 7.8 ConnectionFactory.java
[...]
import java.io.InputStream;
public interface ConnectionFactory {
InputStream getData() throws Exception;
}
The WebClient code then becomes as shown in listing 7.9. (Changes from the initial
implementation in listing 7.6 are shown in bold.)
Listing 7.9
Refactored WebClient using ConnectionFactory
[...]
import java.io.InputStream;
public class WebClient {
public String getContent(ConnectionFactory connectionFactory) {
StringBuffer content = new StringBuffer();
try {
InputStream is = connectionFactory.getData();
int count;
while (-1 != (count = is.read())) {
content.append( new String( Character.toChars( count ) ) );
}
}
catch (Exception e) {
return null;
}
return content.toString();
}
}
This solution is better because we've made the retrieval of the data content indepen-
dent of the way we get the connection. The first implementation worked only with
URL s using HTTP . The new implementation can work with any standard protocol
( file:// , http:// , ftp:// , jar:// , and so forth) or even your own custom protocol.
For example, listing 7.10 shows the ConnectionFactory implementation for HTTP .
Listing 7.10 HttpURLConnectionFactory.java
[...]
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionFactory implements ConnectionFactory {
private URL url;
public HttpURLConnectionFactory(URL url) {
this .url = url;
}
public InputStream getData() throws Exception {
HttpURLConnection connection =
(HttpURLConnection) this.url.openConnection();
 
 
 
 
Search WWH ::




Custom Search