Skip to content

Instantly share code, notes, and snippets.

@thaniaclair
Last active December 17, 2015 05:49
Show Gist options
  • Save thaniaclair/5561070 to your computer and use it in GitHub Desktop.
Save thaniaclair/5561070 to your computer and use it in GitHub Desktop.
Recupera o conteúdo de uma URL.
import java.io.ByteArrayOutputStream;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
/**
* Efetua conexão em URLs para recuperar seu conteúdo.
* @author thania.clair
*/
public class URLConnector {
private static final Logger logger = Logger.getLogger(URLConnector.class);
private String url;
public URLConnector(String pURL) {
this.url = pURL;
}
/**
* Recupera o conteúdo de uma URL, através de uma conexão HHTP.
* @return o conteúdo da URL em formato {@link String}.
*/
public String getContent() {
String content = null;
try {
URL objURL = new URL(url);
ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream();
IOUtils.copy(objURL.openStream(), urlOutputStream);
content = urlOutputStream.toString();
} catch (Exception e) {
logger.warn("URLConnector#getContent, URL = " + url + ", Erro: " + e.getMessage());
}
return content;
}
/**
* Recupera o conteúdo de uma URL, através de uma conexão HHTP.
* @return o conteúdo da URL em formato {@link JSONArray}.
*/
public JSONArray getJSONContent() {
JSONArray json = new JSONArray();
try {
String content = getContent();
if (StringUtils.isBlank(content)) return json;
if (!isArray(content)) return json;
json = new JSONArray(content);
} catch (JSONException je) {
logger.warn("URLConnector#getJSONContent, URL = " + url + ", Erro: " + je.getMessage());
}
return json;
}
/**
* Verifica se o conteúdo repassado é um array.
* @param content conteúdo resultado da requisição da URL.
* @return <code>true</code> se o conteúdo é um array e <code>false</code> caso contrário.
*/
private boolean isArray(String content) {
return content.startsWith("[") && content.endsWith("]");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment