cz.mmsparams.api.http.HttpGetUtil Maven / Gradle / Ivy
package cz.mmsparams.api.http;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.annotation.Nonnull;
import cz.mmsparams.api.logging.APILoggerFactory;
import cz.mmsparams.api.logging.ApiLogFacade;
import cz.mmsparams.api.logging.ILogger;
import cz.mmsparams.api.utils.LogUtil;
public class HttpGetUtil
{
private static final ILogger LOGGER = APILoggerFactory.getLogger(HttpGetUtil.class);
private HttpGetUtil()
{
}
@Nonnull
public static TaskResult getDataFromUrl(final String url)
{
HttpURLConnection conn = null;
try
{
final URL u = new URL(url);
conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setUseCaches(true);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
final int status = conn.getResponseCode();
switch (status)
{
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
{
sb.append(line).append(LogUtil.NEW_LINE);
}
br.close();
return new TaskResult<>(sb.toString());
default:
return new TaskResult<>(new Exception("Invalid status code: " + status));
}
}
catch (Exception e)
{
ApiLogFacade.logEx(LOGGER, "getDataFromUrl", e);
return new TaskResult<>(e);
}
finally
{
if (conn != null)
{
try
{
conn.disconnect();
}
catch (Exception ex)
{
ApiLogFacade.logEx(LOGGER, "getDataFromUrl", ex);
}
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy