Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

In this page you can find the example usage for java.net HttpURLConnection disconnect.

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java

private Bitmap getImageBitmap(String url) {
    Bitmap bm = null;//from  ww  w  .  j av a2 s  . co  m
    try {
        URL aURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
        long ifs = 0;
        ifs = conn.getContentLength();
        if (ifs == -1) {
            conn.disconnect();
            conn = (HttpURLConnection) aURL.openConnection();
            ifs = conn.getContentLength();
        }
        vArtExists = false;
        if (ifs > 0) {
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            vArtExists = true;
            //Log.d("EMD - ","art exists - Hurray!");
        } else {
            Log.e("EMD - ", "art fail ifs 0 " + ifs + " " + url);
        }
    } catch (IOException e) {
        vArtExists = false;
        Log.e("EMD - ", "art fail");
    }
    return bm;
}

From source file:com.reactivetechnologies.jaxrs.RestServerTest.java

static String sendDelete(String url, String content) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;/*  ww  w .  j  a v  a 2 s .c  o  m*/
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("DELETE");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeUTF(content);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java

protected int sendContent(String url, String fileContent, String user, String password) throws IOException {
    HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
    try {//  w  w  w . j av  a  2  s .c o  m
        c.setDoOutput(true);
        c.setRequestMethod("PUT");
        if (user != null) {
            c.setRequestProperty("Authorization",
                    "Basic " + Base64.encodeBase64String((user + ":" + password).getBytes("utf-8")));
        }
        c.connect();
        IOUtils.copy(new ByteArrayInputStream(fileContent.getBytes("utf-8")), c.getOutputStream());
        return c.getResponseCode();
    } finally {
        c.disconnect();
    }
}

From source file:bolts.WebViewAppLinkResolver.java

@Override
public Task<AppLink> getAppLinkFromUrlInBackground(final Uri url) {
    final Capture<String> content = new Capture<String>();
    final Capture<String> contentType = new Capture<String>();
    return Task.callInBackground(new Callable<Void>() {
        @Override/*from w  ww.  j  a  va  2  s.  c om*/
        public Void call() throws Exception {
            URL currentURL = new URL(url.toString());
            URLConnection connection = null;
            while (currentURL != null) {
                // Fetch the content at the given URL.
                connection = currentURL.openConnection();
                if (connection instanceof HttpURLConnection) {
                    // Unfortunately, this doesn't actually follow redirects if they go from http->https,
                    // so we have to do that manually.
                    ((HttpURLConnection) connection).setInstanceFollowRedirects(true);
                }
                connection.setRequestProperty(PREFER_HEADER, META_TAG_PREFIX);
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() >= 300 && httpConnection.getResponseCode() < 400) {
                        currentURL = new URL(httpConnection.getHeaderField("Location"));
                        httpConnection.disconnect();
                    } else {
                        currentURL = null;
                    }
                } else {
                    currentURL = null;
                }
            }

            try {
                content.set(readFromConnection(connection));
                contentType.set(connection.getContentType());
            } finally {
                if (connection instanceof HttpURLConnection) {
                    ((HttpURLConnection) connection).disconnect();
                }
            }
            return null;
        }
    }).onSuccessTask(new Continuation<Void, Task<JSONArray>>() {
        @Override
        public Task<JSONArray> then(Task<Void> task) throws Exception {
            // Load the content in a WebView and use JavaScript to extract the meta tags.
            final TaskCompletionSource<JSONArray> tcs = new TaskCompletionSource<>();
            final WebView webView = new WebView(context);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setNetworkAvailable(false);
            webView.setWebViewClient(new WebViewClient() {
                private boolean loaded = false;

                private void runJavaScript(WebView view) {
                    if (!loaded) {
                        // After the first resource has been loaded (which will be the pre-populated data)
                        // run the JavaScript meta tag extraction script
                        loaded = true;
                        view.loadUrl(TAG_EXTRACTION_JAVASCRIPT);
                    }
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    runJavaScript(view);
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    super.onLoadResource(view, url);
                    runJavaScript(view);
                }
            });
            // Inject an object that will receive the JSON for the extracted JavaScript tags
            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void setValue(String value) {
                    try {
                        tcs.trySetResult(new JSONArray(value));
                    } catch (JSONException e) {
                        tcs.trySetError(e);
                    }
                }
            }, "boltsWebViewAppLinkResolverResult");
            String inferredContentType = null;
            if (contentType.get() != null) {
                inferredContentType = contentType.get().split(";")[0];
            }
            webView.loadDataWithBaseURL(url.toString(), content.get(), inferredContentType, null, null);
            return tcs.getTask();
        }
    }, Task.UI_THREAD_EXECUTOR).onSuccess(new Continuation<JSONArray, AppLink>() {
        @Override
        public AppLink then(Task<JSONArray> task) throws Exception {
            Map<String, Object> alData = parseAlData(task.getResult());
            AppLink appLink = makeAppLinkFromAlData(alData, url);
            return appLink;
        }
    });
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedPUTUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }//from   w ww .j a v  a  2 s  .c o  m

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "PUT", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    connection.setReadTimeout(3000);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.setChunkedStreamingMode(10);
    connection.connect();

    try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), UTF_8)) {
        out.write(TEST_DATA);
    } finally {
        connection.disconnect();
    }

    // Wait for file to become available
    for (int i = 0; i < 10; i++) {
        Thread.sleep(500);

        if (mantaClient.existsAndIsAccessible(path)) {
            break;
        }
    }

    String actual = mantaClient.getAsString(path);
    Assert.assertEquals(actual, TEST_DATA);
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<Note> getNotes(String userID) throws Exception {
    // Server URL setup
    String _url = getBaseUri().appendPath("Notes").appendPath(userID).build().toString();
    Log.d("GETNOTES", _url);
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/*  w w w  .ja v a 2 s. co m*/

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    // Initialize ObjectMapper
    List<Note> noteList = new ArrayList<Note>();
    List<String> noteIds = new ArrayList<String>();
    final JsonNode noteArray = MAPPER.readTree(response).get(Keys.Note.LIST);

    if (noteArray.isArray()) {
        for (final JsonNode noteNode : noteArray) {
            Note n = NotesDatabaseAdapter.getNote(JsonUtils.getJSONValue(noteNode, Keys.Note.ID));
            n.setCreatedBy(JsonUtils.getJSONValue(noteNode, Keys.Note.CREATED_BY));
            if (n != null) {
                noteList.add(n);
            }
            noteIds.add(noteNode.get(Keys.Note.ID).asText());
        }
    } else {
        Log.e(TAG, "Error parsing user's notes list");
    }

    conn.disconnect();
    return noteList;
}

From source file:it.openyoureyes.test.panoramio.Panoramio.java

public List<GeoItem> examinePanoramio(Location current, double distance, Drawable myImage, Intent intent) {
    ArrayList<GeoItem> result = new ArrayList<GeoItem>();

    /*/* w  ww  . j  a v a  2 s  .c o m*/
     * var requiero_fotos = new Json.Remote(
     * "http://www.panoramio.com/map/get_panoramas.php?order=popularity&
     * set=
     * full&from=0&to=10&minx=-5.8&miny=42.59&maxx=-5.5&maxy=42.65&size=
     * medium "
     */
    Location loc1 = new Location("test");
    Location loc2 = new Location("test_");
    AbstractGeoItem.calcDestination(current.getLatitude(), current.getLongitude(), 225, distance / 2, loc1);
    AbstractGeoItem.calcDestination(current.getLatitude(), current.getLongitude(), 45, distance / 2, loc2);
    try {
        URL url = new URL(
                "http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=full&from=0&to=10&minx="
                        + loc1.getLongitude() + "&miny=" + loc1.getLatitude() + "&maxx=" + loc2.getLongitude()
                        + "&maxy=" + loc2.getLatitude() + "&size=thumbnail");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuffer buf = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            buf.append(line + " ");
        }
        reader.close();
        is.close();
        conn.disconnect();
        // while (is.read(buffer) != -1);
        String jsontext = buf.toString();
        Log.d("Json Panoramio", jsontext);
        JSONObject entrie = new JSONObject(jsontext);
        JSONArray arr = entrie.getJSONArray("photos");
        for (int i = 0; i < arr.length(); i++) {
            JSONObject panoramioObj = arr.getJSONObject(i);
            double longitude = panoramioObj.getDouble("longitude");
            double latitude = panoramioObj.getDouble("latitude");
            String urlFoto = panoramioObj.getString("photo_file_url");
            String idFoto = panoramioObj.getString("photo_id");
            Bundle bu = intent.getExtras();
            if (bu == null)
                bu = new Bundle();
            bu.putString("id", idFoto);
            intent.replaceExtras(bu);
            BitmapDrawable bb = new BitmapDrawable(downloadFile(urlFoto));
            PanoramioItem item = new PanoramioItem(latitude, longitude, false, bb, intent);
            result.add(item);
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result;

}

From source file:fyp.project.asyncTask.Http_GetPost.java

public void GET(String url, String val) throws IOException {
    String result = "";
    URL url2 = new URL(url + val);
    HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection();
    int code = urlConnection.getResponseCode();
    try {//from  w  w w  .ja v  a  2  s. c  o m
        if (code == 404) {
            webpage_output = null;
        } else {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            result = convertInputStreamToString(in);
            webpage_output = result;

        }
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    } finally {
        urlConnection.disconnect();
    }

}

From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java

/**
 * Sends data to the specified url via a HTTP POST, and returns the reply
 * @param connection the http url connection to send the request to
 * @param paramsMap a map of attribute=value pairs representing the data to send
 * @param stripOuterXML true if this was originally a POST request, false if a GET request
 * @return the response from the url//  ww w . j  a  v  a  2s  . c  o  m
 * @throws IOException when there's some kind of communication problem
 */
protected String send(HttpURLConnection connection, Map<String, String> paramsMap, boolean stripOuterXML)
        throws IOException {

    // encode data and send query
    sendData(connection, encodeData(paramsMap));

    //retrieve reply
    String result = getReply(connection.getInputStream());
    connection.disconnect();

    if (stripOuterXML)
        result = stripOuterElement(result);
    return result;

}

From source file:alluxio.yarn.ApplicationMaster.java

/**
 * Checks if an Alluxio master node is already running
 * or not on the master address given./*from   ww w . j a v a2s.  c  o  m*/
 *
 * @return true if master exists, false otherwise
 */
private boolean masterExists() {

    String webPort = Configuration.get(PropertyKey.MASTER_WEB_PORT);

    try {
        URL myURL = new URL(
                "http://" + mMasterAddress + ":" + webPort + Constants.REST_API_PREFIX + "/master/version");
        LOG.debug("Checking for master at: " + myURL.toString());
        HttpURLConnection connection = (HttpURLConnection) myURL.openConnection();
        connection.setRequestMethod(HttpMethod.GET);
        int resCode = connection.getResponseCode();
        LOG.debug("Response code from master was: " + Integer.toString(resCode));

        connection.disconnect();
        return resCode == HttpURLConnection.HTTP_OK;
    } catch (MalformedURLException e) {
        LOG.error("Malformed URL in attempt to check if master is running already", e);
    } catch (IOException e) {
        LOG.debug("No existing master found", e);
    }

    return false;
}