diff --git a/approvaltests-util/src/main/java/com/spun/util/io/NetUtils.java b/approvaltests-util/src/main/java/com/spun/util/io/NetUtils.java index c30c29927..0982d0e0a 100644 --- a/approvaltests-util/src/main/java/com/spun/util/io/NetUtils.java +++ b/approvaltests-util/src/main/java/com/spun/util/io/NetUtils.java @@ -1,10 +1,11 @@ package com.spun.util.io; import com.spun.util.ObjectUtils; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.GetMethod; +import java.io.BufferedReader; import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; import java.net.URL; /** @@ -14,34 +15,77 @@ public class NetUtils { public static String loadWebPage(String url, String parameters) { + HttpURLConnection connection = null; try { - HttpClient client = new HttpClient(); - GetMethod method = new GetMethod(url); - if (parameters != null) + if (parameters != null && !parameters.isEmpty()) { - method.setQueryString(parameters); + url += "?" + parameters; } - client.executeMethod(method); - String html = method.getResponseBodyAsString(); - return html; + URL urlObj = new URL(url); + connection = (HttpURLConnection) urlObj.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int responseCode = connection.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) + { + throw new RuntimeException("Failed to load web page, response code: " + responseCode); + } + + InputStream inputStream = connection.getInputStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder html = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) + { + html.append(line); + } + reader.close(); + return html.toString(); } catch (Exception e) { throw ObjectUtils.throwAsError(e); } + finally + { + if (connection != null) + { + connection.disconnect(); + } + } } + public static String readWebpage(String query) { + HttpURLConnection connection = null; try { URL url = new URL(query); - InputStream inputStream = url.openStream(); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.connect(); + + int responseCode = connection.getResponseCode(); + if (responseCode != HttpURLConnection.HTTP_OK) + { + throw new RuntimeException("Failed to read web page, response code: " + responseCode); + } + + InputStream inputStream = connection.getInputStream(); return FileUtils.readStream(inputStream); } catch (Exception e) { throw ObjectUtils.throwAsError(e); } + finally + { + if (connection != null) + { + connection.disconnect(); + } + } } }