Created
December 9, 2014 13:23
-
-
Save josejuansanchez/186dab6b2522e1e8b087 to your computer and use it in GitHub Desktop.
Code Snippet de cómo realizar una petición HTTP con HttpURLConnection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private String checkWeatherAPI(String ApiUrl, String q) { | |
HttpURLConnection urlConnection = null; | |
BufferedReader reader = null; | |
// Almacenará la respuesta JSON como una cadena | |
String weatherJsonStr = null; | |
try { | |
// Codificamos el nombre de la ciudad en UTF8 | |
q = URLEncoder.encode(q, "UTF-8"); | |
// Construimos la URL para hacer la consulta al servicio: OpenWeatherMap | |
// Más info: http://openweathermap.org/API | |
URL url = new URL(ApiUrl + q); | |
// Creamos la petición para OpenWeatherMap y abrimos la conexión | |
urlConnection = (HttpURLConnection) url.openConnection(); | |
urlConnection.setRequestMethod("GET"); | |
urlConnection.connect(); | |
// Leemos el input stream y lo convertimos a un String | |
InputStream inputStream = urlConnection.getInputStream(); | |
StringBuffer buffer = new StringBuffer(); | |
if (inputStream == null) { | |
// No hay respuesta | |
weatherJsonStr = null; | |
} | |
reader = new BufferedReader(new InputStreamReader(inputStream)); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
// No es necesario añadir el salto de línea "\n", además esto no afectará al parseo. | |
// El uso de saltos de línea nos puede ayudar a la hora de depurar los mensajes, | |
buffer.append(line + "\n"); | |
} | |
if (buffer.length() == 0) { | |
// El stream está vacío | |
weatherJsonStr = null; | |
} else { | |
weatherJsonStr = buffer.toString(); | |
} | |
} catch (IOException e) { | |
Log.e(TAG, "Error ", e); | |
weatherJsonStr = null; | |
} finally{ | |
if (urlConnection != null) { | |
urlConnection.disconnect(); | |
} | |
if (reader != null) { | |
try { | |
reader.close(); | |
} catch (final IOException e) { | |
Log.e(TAG, "Error cerrando el stream", e); | |
} | |
} | |
} | |
return weatherJsonStr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment