List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:au.org.ala.fielddata.mobile.service.WebServiceClient.java
protected void close(HttpURLConnection connection) { if (connection != null) { try {/*from w w w. j a v a 2 s . c o m*/ connection.disconnect(); } catch (Exception e) { Log.e("WebServiceClient", "Error closing connection: ", e); } } }
From source file:jmc.util.UtlFbComents.java
public static void getURLComentarios(String url, Long numComents) throws JMCException { File f = null;/*from w w w .j a v a2 s . co m*/ try { Properties props = ConfigPropiedades.getProperties("props_config.properties"); CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL ur = new URL( "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream"); HttpURLConnection cn = (HttpURLConnection) ur.openConnection(); cn.setRequestProperty("user-agent", props.getProperty("navegador")); cn.setInstanceFollowRedirects(false); cn.setUseCaches(false); cn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream())); String dirTempHtml = props.getProperty("archive_json") + "/"; File fld = new File(dirTempHtml); boolean creado = fld.exists() ? true : fld.mkdir(); if (creado) { String archFile = "archivo.json"; String archivo = dirTempHtml + archFile; String linea = null; f = new File(archivo); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); while ((linea = br.readLine()) != null) { bw.append(linea); } bw.close(); cn.disconnect(); List<Fbcoment> lfb = Convertidor.getFbcomentObjects(1l, archivo); // Fbcoment.actComents(idContenido, lfb); } else { cn.disconnect(); } } catch (IOException e) { throw new JMCException(e); } }
From source file:jmc.util.UtlFbComents.java
public static void getComentarios(Long idContenido, Long numComents) throws JMCException { File f = null;// w ww . j a va 2s .c o m try { Properties props = ConfigPropiedades.getProperties("props_config.properties"); CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL ur = new URL("http://graph.facebook.com/comments?id=" + Contenido.getContenido("Where cont_id = '" + idContenido + "'").get(0).getEnlaceURL() + "&limit=" + numComents + "&filter=stream"); HttpURLConnection cn = (HttpURLConnection) ur.openConnection(); cn.setRequestProperty("user-agent", props.getProperty("navegador")); cn.setInstanceFollowRedirects(false); cn.setUseCaches(false); cn.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream())); String dirTempHtml = props.getProperty("archive_json") + "/"; File fld = new File(dirTempHtml); boolean creado = fld.exists() ? true : fld.mkdir(); if (creado) { String archFile = idContenido + ".json"; String archivo = dirTempHtml + archFile; String linea = null; f = new File(archivo); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); while ((linea = br.readLine()) != null) { bw.append(linea); } bw.close(); cn.disconnect(); List<Fbcoment> lfb = Convertidor.getFbcomentObjects(idContenido, archivo); Fbcoment.actComents(idContenido, lfb); } else { cn.disconnect(); } } catch (IOException e) { throw new JMCException(e); } }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
public static String get(String endpoint) { URL url = null;/*from www . j a v a 2 s . c o m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { //Fail silently } HttpURLConnection conn; long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) { try { conn = makeGetConnection(url); // handle the response int status = conn.getResponseCode(); if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); if (null != conn) { conn.disconnect(); } return sb.toString(); } else if (500 > status) { if (null != conn) { conn.disconnect(); } return null; } } catch (IOException e) { try { Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Thread.currentThread().interrupt(); } // increase backoff exponentially backoff *= 2; } } return null; }
From source file:com.thomaskuenneth.openweathermapweather.WeatherUtils.java
public static String getFromServer(String url) throws MalformedURLException, IOException { StringBuilder sb = new StringBuilder(); URL _url = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) _url.openConnection(); String contentType = httpURLConnection.getContentType(); String charSet = "ISO-8859-1"; if (contentType != null) { Matcher m = PATTERN_CHARSET.matcher(contentType); if (m.matches()) { charSet = m.group(1);//from w w w. ja v a 2 s .c om } } final int responseCode = httpURLConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream(), charSet); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(line); } try { bufferedReader.close(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, "getFromServer()", ex); } } httpURLConnection.disconnect(); return sb.toString(); }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
public static String get(String endpoint, Map<String, String> params) { URL url = null;/* w w w . java 2 s . c o m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { //Fail silently } byte[] bytes = constructParams(params); HttpURLConnection conn; long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) { try { conn = makeGetConnection(url, bytes); // handle the response int status = conn.getResponseCode(); if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); if (null != conn) { conn.disconnect(); } return sb.toString(); } else if (500 > status) { if (null != conn) { conn.disconnect(); } return null; } } catch (IOException e) { try { Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Thread.currentThread().interrupt(); } // increase backoff exponentially backoff *= 2; } } return null; }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
/** * Issue a POST request to the server, and return the results from it as a string * //www . ja v a 2 s . com * @param endpoint * POST address. * @param params * request parameters. * * @throws IOException * propagated from POST. */ public static String postForResults(String endpoint, Map<String, String> params) { URL url = null; try { url = new URL(endpoint); } catch (MalformedURLException e) { //Fail silently } byte[] bytes = constructParams(params); HttpURLConnection conn; long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); for (int i = 1; i <= HttpUtilities.MAX_ATTEMPTS; i++) { try { conn = makePostConnection(url, bytes); // handle the response int status = conn.getResponseCode(); if (status == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); if (null != conn) { conn.disconnect(); } return sb.toString(); } else if (500 > status) { if (null != conn) { conn.disconnect(); } return null; } } catch (IOException e) { try { Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Thread.currentThread().interrupt(); } // increase backoff exponentially backoff *= 2; } } return null; }
From source file:com.memetix.mst.MicrosoftTranslatorAPI.java
/** * Forms an HTTP request, sends it using GET method and returns the result of the request as a String. * /*from www .java 2 s .c om*/ * @param url The URL to query for a String response. * @return The translated String. * @throws Exception on error. */ private static String retrieveResponse(final URL url) throws Exception { if (clientId != null && clientSecret != null && System.currentTimeMillis() > tokenExpiration) { String tokenJson = getToken(clientId, clientSecret); Integer expiresIn = Integer .parseInt((String) ((JSONObject) JSONValue.parse(tokenJson)).get("expires_in")); tokenExpiration = System.currentTimeMillis() + ((expiresIn * 1000) - 1); token = "Bearer " + (String) ((JSONObject) JSONValue.parse(tokenJson)).get("access_token"); } final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", contentType + "; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); if (token != null) { uc.setRequestProperty("Authorization", token); } uc.setRequestMethod("GET"); uc.setDoOutput(true); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Microsoft Translator API: " + result); } return result; } finally { if (uc != null) { uc.disconnect(); } } }
From source file:com.example.android.didyoufeelit.Utils.java
/** * Make an HTTP request to the given URL and return a String as the response. *///from w w w . j a va2 s .c om private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; }
From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java
@Nullable public static CircularArray<WeatherData> getWeatherForWoeids(CircularArray<String> woeids, String unit) throws CantGetWeatherException { if (woeids == null || woeids.isEmpty()) return null; HttpURLConnection connection = null; try {/*from ww w . j av a 2s . co m*/ String url = buildWeatherQueryUrl(woeids, unit); if (BuildConfig.DEBUG) Log.d("YahooWeatherApiClient", "loading weather from: " + url); connection = Utils.openUrlConnection(url); CircularArray<WeatherData> result = new CircularArray<>(); WeatherDataParser.parseWeatherData(result, connection.getInputStream(), woeids); return result; } catch (JSONException | ResponseParserException | ParseException | IOException | NumberFormatException e) { throw new CantGetWeatherException(true, R.string.no_weather_data, "Error parsing weather feed XML.", e); } finally { if (connection != null) { connection.disconnect(); } } }