Created
December 17, 2016 15:58
-
-
Save Canx/fe918bf2950c2e12588f4967fe0293df to your computer and use it in GitHub Desktop.
método estático que puedes incluir en tus clientes REST
This file contains hidden or 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
public static JSONObject requestWebService(String serviceUrl) { | |
disableConnectionReuseIfNecessary(); | |
HttpURLConnection urlConnection = null; | |
try { | |
// create connection | |
URL urlToRequest = new URL(serviceUrl); | |
urlConnection = (HttpURLConnection) | |
urlToRequest.openConnection(); | |
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); | |
urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT); | |
// handle issues | |
int statusCode = urlConnection.getResponseCode(); | |
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { | |
// handle unauthorized (if service requires user login) | |
} else if (statusCode != HttpURLConnection.HTTP_OK) { | |
// handle any other errors, like 404, 500,.. | |
} | |
// create JSON object from content | |
InputStream in = new BufferedInputStream( | |
urlConnection.getInputStream()); | |
return new JSONObject(getResponseText(in)); | |
} catch (MalformedURLException e) { | |
// URL is invalid | |
} catch (SocketTimeoutException e) { | |
// data retrieval or connection timed out | |
} catch (IOException e) { | |
// could not read response body | |
// (could not create input stream) | |
} catch (JSONException e) { | |
// response body is no valid JSON string | |
} finally { | |
if (urlConnection != null) { | |
urlConnection.disconnect(); | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment