List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:info.tongrenlu.android.helper.HttpHelper.java
static public JSONObject loadJSON(String url) { HttpURLConnection connection = null; JSONObject json = null;/* w ww . j a v a2 s.c o m*/ InputStream is = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); is = new BufferedInputStream(connection.getInputStream()); json = new JSONObject(convertStreamToString(is)); } catch (IOException ioe) { ioe.printStackTrace(); } catch (JSONException je) { je.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } if (connection != null) { connection.disconnect(); } } return json; }
From source file:org.apache.felix.http.itest.BaseIntegrationTest.java
protected static void assertContent(int expectedRC, String expected, URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); int rc = conn.getResponseCode(); assertEquals("Unexpected response code,", expectedRC, rc); if (rc >= 200 && rc < 500) { InputStream is = null;/*from ww w. j a v a 2 s .c om*/ try { is = conn.getInputStream(); assertEquals(expected, slurpAsString(is)); } finally { close(is); conn.disconnect(); } } else { InputStream is = null; try { is = conn.getErrorStream(); assertEquals(expected, slurpAsString(is)); } finally { close(is); conn.disconnect(); } } }
From source file:com.appsimobile.appsii.module.weather.loader.YahooWeatherApiClient.java
public static CircularArray<LocationSearchResult> findLocationsAutocomplete(String startsWith) { CircularArray<LocationSearchResult> results = new CircularArray<>(); HttpURLConnection connection = null; try {/*w w w .jav a 2s .c om*/ connection = Utils.openUrlConnection(buildPlaceSearchStartsWithUrl(startsWith)); InputStream inputStream = connection.getInputStream(); parseLocationSearchResults(results, inputStream); } catch (IOException | XmlPullParserException e) { Log.w(TAG, "Error parsing place search XML"); } finally { if (connection != null) { connection.disconnect(); } } return results; }
From source file:com.arthurpitman.common.HttpUtils.java
/** * Retrieves a URL as a string./*from ww w . j av a 2 s . c o m*/ * @param url * @param requestProperties optional request properties, <code>null</code> if not required. * @param postData optional post data, <code>null</code> if not required. * @return a {@link String} representing the response. * @throws IOException */ public static String retrieveUrlAsString(final String url, final RequestProperty[] requestProperties, final byte[] postData) throws IOException { for (int i = 0;; i++) { HttpURLConnection connection = null; try { if (postData != null) { connection = connectPost(url, requestProperties, postData); } else { connection = connectGet(url, requestProperties); } return StreamUtils.readStreamIntoString(connection.getInputStream(), UTF8_CHARACTER_SET, BUFFER_SIZE); } catch (IOException e) { if (i == CONNECTION_RETRIES) { throw e; } } finally { // always close the connection if (connection != null) { connection.disconnect(); } } // allow recovery time try { Thread.sleep(CONNECTION_RETRY_SLEEP); } catch (InterruptedException e) { } } }
From source file:com.appdynamics.common.RESTClient.java
public static void sendGet(String urlString, String apiKey) { try {/*from www . j a va 2 s . c om*/ URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((apiKey).getBytes()))); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.info("Output from Server .... \n"); while ((output = br.readLine()) != null) { logger.info(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.pureinfo.srm.outlay.action.SearchCheckCodeAction.java
/** * //w ww . j a v a 2 s . co m * @param strUrl * @param strPostRequest * @return */ public static String getPageContent(String strUrl, String strPostRequest) { // StringBuffer buffer = new StringBuffer(); System.setProperty("sun.net.client.defaultConnectTimeout", "5000"); System.setProperty("sun.net.client.defaultReadTimeout", "5000"); try { URL newUrl = new URL(strUrl); HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection(); //POST if (strPostRequest.length() > 0) { hConnect.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream()); out.write(strPostRequest); out.flush(); out.close(); } // BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream())); int ch; for (int length = 0; (ch = rd.read()) > -1; length++) buffer.append((char) ch); rd.close(); hConnect.disconnect(); return buffer.toString().trim(); } catch (Exception e) { // return ":"; return null; } finally { buffer.setLength(0); } }
From source file:com.example.prathik1.drfarm.OCRRestAPI.java
private static void DownloadConvertedFile(String outputFileUrl) throws IOException { URL downloadUrl = new URL(outputFileUrl); HttpURLConnection downloadConnection = (HttpURLConnection) downloadUrl.openConnection(); if (downloadConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = downloadConnection.getInputStream(); // opens an output stream to save into file FileOutputStream outputStream = new FileOutputStream("C:\\converted_file.doc"); int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); }// w w w. ja v a 2 s . c om outputStream.close(); inputStream.close(); } downloadConnection.disconnect(); }
From source file:dk.nsi.minlog.test.utils.TestHelper.java
public static String sendRequest(String url, String action, String docXml, boolean failOnError) throws IOException, ServiceException { URL u = new URL(url); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); uc.setDoOutput(true);/*from www . jav a 2s . c o m*/ uc.setDoInput(true); uc.setRequestMethod("POST"); uc.setRequestProperty("SOAPAction", "\"" + action + "\""); uc.setRequestProperty("Content-Type", "text/xml; charset=utf-8;"); OutputStream os = uc.getOutputStream(); IOUtils.write(docXml, os, "UTF-8"); os.flush(); os.close(); InputStream is; if (uc.getResponseCode() != 200) { is = uc.getErrorStream(); } else { is = uc.getInputStream(); } String res = IOUtils.toString(is); is.close(); if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) { throw new ServiceException(res); } uc.disconnect(); return res; }
From source file:Main.java
public static String executePost(String url, String parameters) throws IOException { URL request = new URL(url); HttpURLConnection connection = (HttpURLConnection) request.openConnection(); connection.setDoOutput(true);/*w w w .ja va 2 s. c om*/ connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", "StripeConnectAndroid"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length)); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(parameters); wr.flush(); wr.close(); String response = streamToString(connection.getInputStream()); connection.disconnect(); return response; }
From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java
public static boolean deleteAgenda(String agendaID) throws IOException { // Server URL setup String _url = getBaseUri().appendPath(agendaID).build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.DELETE); addRequestHeader(conn, false);//from w w w. ja v a 2s .c o m // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); boolean result = false; JsonNode tree = MAPPER.readTree(response); if (!response.isEmpty()) { if (!tree.has(Keys.DELETED)) { result = true; } else { Log.e(TAG, String.format("ErrorID: [%s] %s", tree.get(Keys.ERROR_ID).asText(), tree.get(Keys.ERROR_MESSAGE).asText())); } } conn.disconnect(); return result; }