List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:com.matthewmitchell.nubits_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;//from w ww . ja v a 2 s . c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.versobit.weatherdoge.WeatherUtil.java
private static WeatherResult getWeatherFromOWM(double latitude, double longitude, String location) { try {//from w w w . ja v a2 s . c o m String query; if (latitude == Double.MIN_VALUE && longitude == Double.MIN_VALUE) { if (location == null) { return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, "No valid location parameters.", new IllegalArgumentException()); } query = "q=" + URLEncoder.encode(location, "UTF-8"); } else { query = "lat=" + URLEncoder.encode(String.valueOf(latitude), "UTF-8") + "&lon=" + URLEncoder.encode(String.valueOf(longitude), "UTF-8"); } query += "&APPID=" + URLEncoder.encode(BuildConfig.OWM_APPID, "UTF-8"); URL url = new URL("http://api.openweathermap.org/data/2.5/weather?" + query); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { JSONObject response = new JSONObject(IOUtils.toString(connection.getInputStream())); if (response.getInt("cod") != HttpURLConnection.HTTP_OK) { // OWM has HTTP error codes that are passed through an API field, the actual HTTP // error code is always 200... return new WeatherResult(null, WeatherResult.ERROR_API, response.getString("cod") + ": " + response.getString("message"), null); } JSONObject weather = response.getJSONArray("weather").getJSONObject(0); JSONObject main = response.getJSONObject("main"); double temp = main.getDouble("temp") - 273.15d; String condition = WordUtils.capitalize(weather.getString("description").trim()); String image = weather.getString("icon"); if (location == null || location.isEmpty()) { location = response.getString("name"); } return new WeatherResult(new WeatherData(temp, condition, image, latitude, longitude, location, new Date(), Source.OPEN_WEATHER_MAP), WeatherResult.ERROR_NONE, null, null); } finally { connection.disconnect(); } } catch (Exception ex) { return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, ex.getMessage(), ex); } }
From source file:com.vaguehope.onosendai.util.HttpHelper.java
private static <R> R fetchWithFollowRedirects(final Method method, final URL url, final HttpStreamHandler<R> streamHandler, final int redirectCount) throws IOException, URISyntaxException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try {//from ww w . j ava 2 s . co m connection.setRequestMethod(method.toString()); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_CONNECT_TIMEOUT_SECONDS)); connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(HTTP_READ_TIMEOUT_SECONDS)); connection.setRequestProperty("User-Agent", "curl/1"); // Make it really clear this is not a browser. //connection.setRequestProperty("Accept-Encoding", "identity"); This fixes missing Content-Length headers but feels wrong. connection.connect(); InputStream is = null; try { final int responseCode = connection.getResponseCode(); // For some reason some devices do not follow redirects. :( if (responseCode == 301 || responseCode == 302 || responseCode == 303 || responseCode == 307) { // NOSONAR not magic numbers. Its HTTP spec. if (redirectCount >= MAX_REDIRECTS) throw new TooManyRedirectsException(responseCode, url, MAX_REDIRECTS); final String locationHeader = connection.getHeaderField("Location"); if (locationHeader == null) throw new HttpResponseException(responseCode, "Location header missing. Headers present: " + connection.getHeaderFields() + "."); connection.disconnect(); final URL locationUrl; if (locationHeader.toLowerCase(Locale.ENGLISH).startsWith("http")) { locationUrl = new URL(locationHeader); } else { locationUrl = url.toURI().resolve(locationHeader).toURL(); } return fetchWithFollowRedirects(method, locationUrl, streamHandler, redirectCount + 1); } if (responseCode < 200 || responseCode >= 300) { // NOSONAR not magic numbers. Its HTTP spec. throw new NotOkResponseException(responseCode, connection, url); } is = connection.getInputStream(); final int contentLength = connection.getContentLength(); if (contentLength < 1) LOG.w("Content-Length=%s for %s.", contentLength, url); return streamHandler.handleStream(connection, is, contentLength); } finally { IoHelper.closeQuietly(is); } } finally { connection.disconnect(); } }
From source file:com.bushstar.htmlcoin_android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;/* w ww. ja v a2 s . c o m*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, BTCE_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + BTCE_URL, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public void delete(URL uri, Map<String, List<String>> headers) { // DELETE delete = new DELETE(uri, headers); HttpURLConnection httpURLConnection = null; try {//from ww w .j ava2s .c om httpURLConnection = (HttpURLConnection) uri.openConnection(); httpURLConnection.setRequestMethod("DELETE"); //httpURLConnection.connect(); int s = httpURLConnection.getResponseCode(); } catch (IOException exception) { exception.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
From source file:com.spoiledmilk.ibikecph.util.HttpUtils.java
public static JsonResult readLink(String url_string, String method) { JsonResult result = new JsonResult(); if (url_string == null) { return result; }/*from w w w .ja v a2 s.c o m*/ URL url = null; HttpURLConnection httpget = null; try { LOG.d("HttpUtils readlink() " + url_string); url = new URL(url_string); httpget = (HttpURLConnection) url.openConnection(); httpget.setDoInput(true); httpget.setRequestMethod(method); httpget.setRequestProperty("Accept", "application/json"); httpget.setRequestProperty("Content-type", "application/json"); httpget.setConnectTimeout(CONNECTON_TIMEOUT); httpget.setReadTimeout(CONNECTON_TIMEOUT); JsonNode root = null; root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class); if (root != null) { result.setNode(root); } } catch (JsonParseException e) { LOG.w("HttpUtils readLink() JsonParseException ", e); result.error = JsonResult.ErrorCode.APIError; } catch (MalformedURLException e) { LOG.w("HttpUtils readLink() MalformedURLException", e); result.error = JsonResult.ErrorCode.APIError; } catch (FileNotFoundException e) { LOG.w("HttpUtils readLink() FileNotFoundException", e); result.error = JsonResult.ErrorCode.NotFound; } catch (IOException e) { LOG.w("HttpUtils readLink() IOException", e); result.error = JsonResult.ErrorCode.ConnectionError; } finally { if (httpget != null) { httpget.disconnect(); } } LOG.d("HttpUtils readLink() " + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed")); return result; }
From source file:com.ardnezar.lookapp.RoomParametersFetcher.java
private LinkedList<PeerConnection.IceServer> requestTurnServers(String url) throws IOException, JSONException { LinkedList<PeerConnection.IceServer> turnServers = new LinkedList<PeerConnection.IceServer>(); Log.d(TAG, "Request TURN from: " + url); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(TURN_HTTP_TIMEOUT_MS); connection.setReadTimeout(TURN_HTTP_TIMEOUT_MS); int responseCode = connection.getResponseCode(); if (responseCode != 200) { throw new IOException("Non-200 response when requesting TURN server from " + url + " : " + connection.getHeaderField(null)); }/*from ww w . ja va 2 s .c om*/ InputStream responseStream = connection.getInputStream(); String response = drainStream(responseStream); connection.disconnect(); Log.d(TAG, "TURN response: " + response); JSONObject responseJSON = new JSONObject(response); String username = responseJSON.getString("username"); String password = responseJSON.getString("password"); JSONArray turnUris = responseJSON.getJSONArray("uris"); for (int i = 0; i < turnUris.length(); i++) { String uri = turnUris.getString(i); turnServers.add(new PeerConnection.IceServer(uri, username, password)); } return turnServers; }
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
private static String fetch(Uri uri) { HttpURLConnection connection = null; BufferedReader reader = null; String rawJSON = ""; Log.d(TAG, uri.toString());/*w ww . j ava 2 s.c o m*/ try { URL url = new URL(uri.toString()); //java.net Malformed uri exception connection = (HttpURLConnection) url.openConnection(); //java.io. IO exception connection.setRequestMethod("GET"); //java.net.ProtocolException && unnecessary connection.connect(); //java.io.IOExecption InputStream inputStream = connection.getInputStream(); // java.io.IOException StringBuffer stringBuffer = new StringBuffer(); if (inputStream == null) { return rawJSON; } reader = new BufferedReader(new InputStreamReader(inputStream)); //Make the string more readable String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line + "\n"); } rawJSON = stringBuffer.toString(); Log.d(TAG + "doInBackground", rawJSON); } catch (IOException e) { Log.e(TAG, "Error ", e); e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(TAG, "Error closing stream", e); } } } return rawJSON; }
From source file:org.esupportail.nfctagdroid.requestasync.CsnHttpRequestAsync.java
protected String doInBackground(String... params) { CsnMessageBean nfcMsg = new CsnMessageBean(); nfcMsg.setNumeroId(LocalStorage.getValue("numeroId")); nfcMsg.setCsn(params[0]);/* w w w . j a v a 2s . co m*/ ObjectMapper mapper = new ObjectMapper(); String jsonInString = null; try { jsonInString = mapper.writeValueAsString(nfcMsg); URL url = new URL(NfcTacDroidActivity.ESUP_NFC_TAG_SERVER_URL + "/csn-ws"); log.info("Will call csn-ws on : " + url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.connect(); Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); writer.write(jsonInString); writer.close(); InputStream inputStream = conn.getInputStream(); String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); while ((line = br.readLine()) != null) { response += line; } conn.disconnect(); return response; } catch (Exception e) { throw new NfcTagDroidException(e); } }
From source file:com.rimbit.android_wallet.ExchangeRatesProvider.java
private static String getURLResult(URL url, final String userAgent) { HttpURLConnection connection = null; Reader reader = null;//from ww w . j a v a2s. c o m try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); reader = new InputStreamReader(is, Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); return content.toString(); } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, RIMBIT_EXPLORER_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + RIMBIT_EXPLORER_URL, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }