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.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java

private void closeConnection(HttpURLConnection connection) throws IOException {
    connection.getOutputStream().close();
    connection.disconnect();

    // we have to call this, otherwise out HTTP data does not get send, even though close()/disconnect was called
    // Ceterum censeo HttpUrlConnection esse delendam
    if (connection.getResponseCode() != HttpStatus.OK.value()) {
        LOGGER.error("Reporting returned code {} {}: {}", connection.getResponseCode(),
                connection.getResponseMessage());
    }//from   www  . j a v  a2  s .  c  o  m
}

From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java

/**
 * Issue a POST request to the server.// ww  w. j  av a 2 s . c  o  m
 * 
 * @param params request parameters.
 * 
 * @throws IOException propagated from POST.
 */
protected String post(String request) throws IOException {
    URL url = convertAddressToURL();

    byte[] bytes = request.getBytes();

    HttpURLConnection conn = null;
    try {
        conn = setupConnection(url, bytes);
        postRequest(conn, bytes);
        checkHttpStatus(conn);

        return getResult(conn);
    } catch (Exception e) {
        return StringUtils.EMPTY;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:h2weibo.utils.filters.FlickrImageFilter.java

private String extraceFromShortURL(String input) {
    Pattern p = Pattern.compile("flic.kr/p/(\\w+)/?.*");
    Matcher m = p.matcher(input);
    if (m.find()) {
        input = "http://www.flickr.com/photo.gne?short=" + m.group(1);

        String imageUrl = null;//  w ww.  jav a 2  s. c  o  m
        try {
            URL url = new URL(input);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            int code = conn.getResponseCode();
            if (code == 302) {
                String loc = conn.getHeaderField("location");
                imageUrl = extraceFromFullURL("http://www.flickr.com" + loc);
            }
            conn.disconnect();
        } catch (Exception e) {
            log.error("Not able to handle flickr's short url/", e);
        }
        return imageUrl;
    } else {
        return null;
    }
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @return - the direct link//from w  ww.j  a v a 2  s  .c  om
 */
public static String getCreeperhostLink(String file) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/" + file;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        for (String server : downloadServers.values()) {
            if (connection.getResponseCode() != 200) {
                if (!server.contains("creeper")) {
                    file = file.replaceAll("%5E", "/");
                }

                resolved = "http://" + server + "/FTB2/" + file;
                connection = (HttpURLConnection) new URL(resolved).openConnection();
                connection.setRequestProperty("Cache-Control", "no-transform");
                connection.setRequestMethod("HEAD");
            } else {
                break;
            }
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    return resolved;
}

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

public static List<Group> getGroups(String userID) throws IOException {
    // Server URL setup
    System.out.println(userID);/* w  ww .j  av a  2  s.  com*/
    String _url = getBaseUri().appendPath("Groups").appendPath(userID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);

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

    System.out.println("yes");

    // Initialize ObjectMapper
    List<Group> groupList = new ArrayList<Group>();
    List<String> groupIDList = new ArrayList<String>();
    System.out.println("maybe");
    final JsonNode groupArray = MAPPER.readTree(response).get(Keys.Group.LIST);
    System.out.println("no");

    if (groupArray.isArray()) {
        for (final JsonNode groupNode : groupArray) {
            String _id = groupNode.get(Keys.Group.ID).asText();
            System.out.println(_id);
            groupIDList.add(_id);
        }
    }
    conn.disconnect();

    for (String id : groupIDList) {
        groupList.add(GroupDatabaseAdapter.getGroup(id));
    }

    return groupList;
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test read post url disabled.//from w  ww  .ja v  a2s  .c  om
 * 
 *
 * @throws Exception the exception
 */
public void testReadPostURLDisabled() throws Exception {
    HttpURLConnection connection = NetworkUtils.getConnection(URL, null);
    assertNotNull(connection);
    connection.setDoOutput(true);
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "true");
    assertNull(NetworkUtils.readPostURL(connection, "post"));
    connection.disconnect();
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

static String getHttpString(String url) {

    String result = null;/*from  w w  w .  j  a  v  a  2 s .co  m*/

    // build connection
    HttpURLConnection huc = getHUC(url);
    huc.setInstanceFollowRedirects(false);

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getHttpString response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
        } else {
            // result = "response code: "+responseCode;
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Log.e(TAG, "revokeSite FAILED");
        e.printStackTrace();
    }

    return result;
}

From source file:BihuHttpUtil.java

/**
 * ??HTTPJSON?/*  w  w w.  ja v a2  s  .  c o  m*/
 * @param url
 * @param jsonStr
 */
public static String sendPostForJson(String url, String jsonStr) {
    StringBuffer sb = new StringBuffer("");
    try {
        //
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        //POST
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(jsonStr.getBytes("UTF-8"));//???
        out.flush();
        out.close();
        //??
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // 
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java

@Override
protected String doInBackground(String... params) {
    String error = null;/*w ww.j  ava  2 s  .com*/

    URL url = null;

    try {
        // open a stream on URL
        url = new URL(mUrl);
    } catch (MalformedURLException e) {
        error = e.toString();
        e.printStackTrace();
    }

    boolean retry = false;
    HttpURLConnection urlConnection = null;
    int resCode = 0;

    do {
        // create the new connection
        ComicsAuthenticator.sInstance.reset();

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

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(ComicsParameters.TIME_OUT);
            urlConnection.setReadTimeout(ComicsParameters.TIME_OUT);
            resCode = urlConnection.getResponseCode();
        } catch (EOFException e) {
            // under Android 4
            resCode = -1;
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("ComicsReader", "Rescode " + resCode);

        if (resCode < 0) {
            retry = true;
        } else if (resCode == 401) {
            ComicsAuthenticator.sInstance.setResult(false);

            // user pressed cancel
            if (!ComicsAuthenticator.sInstance.isValidated()) {
                return null;
            }

            retry = true;
        } else {
            retry = false;
        }
    } while (retry);

    if (resCode != HttpURLConnection.HTTP_OK) {
        ComicsAuthenticator.sInstance.setResult(false);

        // TODO: HTTP error occurred 
        return null;
    }

    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    InputStream is = null;

    try {
        // download the file
        is = new BufferedInputStream(urlConnection.getInputStream(), ComicsParameters.BUFFER_SIZE);

        int count = 0;
        byte data[] = new byte[ComicsParameters.BUFFER_SIZE];

        while ((count = is.read(data)) != -1) {
            bytes.write(data, 0, count);
        }

        ComicsAuthenticator.sInstance.setResult(true);
    } catch (IOException e) {
        error = e.toString();
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

    if (bytes != null) {
        final String text = new String(bytes.toByteArray());

        if (text.contains("<albums>")) {
            parseXml(text);
        } else if (text.contains("\"albums\":")) {
            parseJson(text);
        } else {
            Log.e("ComicsReader", "Error");
        }
    }

    return error;
}

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

public String send(String urlStr, String data) throws IOException {
    HttpURLConnection connection = initPostConnection(urlStr);
    sendData(connection, data);//from   ww  w.ja v a 2 s. com
    String result = getReply(connection.getInputStream());
    connection.disconnect();

    return result;
}