Skip to content

Commit

Permalink
! r Use java's built in UrlConnection instead of apache http client
Browse files Browse the repository at this point in the history
Co-authored-by: Jay Bazuzi <[email protected]>
Co-authored-by: Llewellyn Falco <[email protected]>
  • Loading branch information
3 people committed Jan 16, 2025
1 parent d8e742b commit 3e5db39
Showing 1 changed file with 54 additions and 10 deletions.
64 changes: 54 additions & 10 deletions approvaltests-util/src/main/java/com/spun/util/io/NetUtils.java
Original file line number Diff line number Diff line change
@@ -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;

/**
Expand All @@ -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();
}
}
}
}

0 comments on commit 3e5db39

Please sign in to comment.