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:net.gcolin.simplerepo.test.AbstractRepoTest.java

protected int getStatus(String url, long lastUpdate) throws IOException {
    HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
    try {//from w ww.  j a va  2  s  .  c o m
        if (lastUpdate > 0) {
            c.setIfModifiedSince(lastUpdate);
        }
        c.setUseCaches(false);
        c.connect();
        return c.getResponseCode();
    } finally {
        c.disconnect();
    }
}

From source file:Main.java

public static String doGet(String urlStr) {
    URL url = null;/*  w  w w . ja  va 2  s. com*/
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
        conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toString();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (baos != null)
                baos.close();
        } catch (IOException e) {
        }
        conn.disconnect();
    }

    return null;

}

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

public static List<Task> getTasks(String userID) throws JsonParseException, JsonMappingException, IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Tasks").appendPath(userID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from w  ww  .j av  a2 s . co  m

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

    // Initialize ObjectMapper
    List<Task> taskList = new ArrayList<Task>();
    final JsonNode taskArray = MAPPER.readTree(response).get(Keys.Task.LIST);

    if (taskArray.isArray()) {
        for (final JsonNode taskNode : taskArray) {
            Task t = TaskDatabaseAdapter.parseTasks(taskNode);
            if (t != null) {
                taskList.add(t);
            }
        }
    } else {
        Log.e(TAG, "Error parsing user's task list");
    }

    conn.disconnect();
    for (Task t : taskList) {
        TaskDatabaseAdapter.getTask(t);
    }
    return taskList;
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

/**
 * Logout and end session//from w w  w  .  j  av  a  2 s  .  c o  m
 * @return
 */
boolean logout() {
    try {
        URL url = new URL(host + "rest/user/logout");
        HttpURLConnection conn = createConnection(url, "POST", false);
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            return false;
        }
        conn.disconnect();
    } catch (Throwable e) {
        throw new OkapiIOException("Error in logout().", e);
    }
    return true;
}

From source file:Main.java

public static byte[] doGet(String urlStr) {
    URL url = null;// w ww  .j a v  a2  s .c  o  m
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
        conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (baos != null)
                baos.close();
        } catch (IOException e) {
        }
        conn.disconnect();
    }

    return null;

}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

public Node getNode(String nodeId) {
    try {/*from www .j  ava 2  s.  com*/
        URL url = new URL(host + String.format("rest/node/%s", nodeId));
        HttpURLConnection conn = createConnection(url, "GET", false);

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            throw new RuntimeException("Error in getNode(): " + conn.getResponseMessage());
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        JSONParser parser = new JSONParser();
        JSONObject node = (JSONObject) parser.parse(reader);

        conn.disconnect();

        return new Node(node);
    } catch (Throwable e) {
        throw new RuntimeException("Error in getNode(): " + e.getMessage(), e);
    }
}

From source file:KV78Tester.java

public String[] getLines() throws Exception {
    String uri = "http://openov.nl:5078/line/";
    URL url = new URL(uri);
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    uc.setRequestProperty("User-Agent", "KV78Turbo-Test");
    uc.setConnectTimeout(60000);/*  ww  w .  j  av a  2s .c  om*/
    uc.setReadTimeout(60000);
    BufferedReader in;
    in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
    try {
        return parseLines(in);
    } finally {
        uc.disconnect();
    }
}

From source file:net.bible.service.common.CommonUtils.java

/** return true if URL is accessible
 * //from   w  w w.j av  a  2s . co m
 * Since Android 3 must do on different or NetworkOnMainThreadException is thrown
 */
public static boolean isHttpUrlAvailable(final String urlString) {
    boolean isAvailable = false;
    final int TIMEOUT_MILLIS = 3000;

    try {
        class CheckUrlThread extends Thread {
            public boolean checkUrlSuccess = false;

            public void run() {
                HttpURLConnection connection = null;
                try {
                    // might as well test for the url we need to access
                    URL url = new URL(urlString);

                    Log.d(TAG, "Opening test connection");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(TIMEOUT_MILLIS);
                    Log.d(TAG, "Connecting to test internet connection");
                    connection.connect();
                    checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
                    Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess);
                } catch (IOException e) {
                    Log.i(TAG, "No internet connection");
                    checkUrlSuccess = false;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }
        ;

        CheckUrlThread checkThread = new CheckUrlThread();
        checkThread.start();
        checkThread.join(TIMEOUT_MILLIS);
        isAvailable = checkThread.checkUrlSuccess;
    } catch (InterruptedException e) {
        Log.e(TAG, "Interrupted waiting for url check to complete", e);
    }
    return isAvailable;
}

From source file:com.clevertrail.mobile.viewtrail.Object_TrailArticle.java

private static int loadTrailArticle_helper(Activity activity, String sTrailName) {

    String sResponseLine = "";
    //sanity check
    if (sTrailName == null || sTrailName == "")
        return R.string.error_notrailname;

    //connect to clevertrail.com to get trail article
    HttpURLConnection urlConnection = null;
    try {// w  w w  .j a v  a  2  s. c om
        String requestURL = String.format("http://clevertrail.com/ajax/handleGetArticleJSONByName.php?name=%s",
                Uri.encode(sTrailName));

        URL url = new URL(requestURL);
        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        BufferedReader r = new BufferedReader(new InputStreamReader(in));

        //trail article in json format
        sResponseLine = r.readLine();

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        // could not connect to clevertrail.com
        e.printStackTrace();
        return R.string.error_contactingclevertrail;
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    JSONObject json = null;
    try {
        if (sResponseLine != "")
            json = new JSONObject(sResponseLine);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return R.string.error_corrupttrailinfo;
    }

    //now that we have the latest trail information, mark it as unsaved
    Object_TrailArticle.bSaved = false;

    // if json is null, we might not have internet activity so check saved
    // files
    if (json == null) {
        Database_SavedTrails db = new Database_SavedTrails(activity);
        db.openToRead();
        String jsonString = db.getJSONString(sTrailName);
        try {
            json = new JSONObject(jsonString);

            // if we found the json object in the db, mark it as saved
            if (json != null) {
                Object_TrailArticle.bSaved = true;
            }

        } catch (JSONException e) {
            return R.string.error_corrupttrailinfo;
        }
        db.close();
    }

    if (json != null) {
        Object_TrailArticle.createFromJSON(sTrailName, json);
        Object_TrailArticle.jsonText = sResponseLine;

        //after loading the data, launch the activity to actually view the trail
        Intent i = new Intent(mActivity, Activity_ViewTrail.class);
        mActivity.startActivity(i);

        return 0;
    }
    return R.string.error_corrupttrailinfo;
}

From source file:net.cbtltd.server.WebService.java

/**
 * Gets the connection to the JSON server.
 *
 * @param url the connection URL./*from  w  ww  . j a  va  2  s  .  c  om*/
 * @param rq the request object.
 * @return the JSON string returned by the message.
 * @throws Throwable the exception thrown by the method.
 */
private static final String getConnection(URL url, String rq) throws Throwable {
    String jsonString = "";
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        //connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        if (rq != null) {
            connection.setRequestProperty("Accept", "application/json");
            connection.connect();
            byte[] outputBytes = rq.getBytes("UTF-8");
            OutputStream os = connection.getOutputStream();
            os.write(outputBytes);
        }

        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        String line;
        while ((line = br.readLine()) != null) {
            jsonString += line;
        }
    } catch (Throwable x) {
        throw new RuntimeException(x.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonString;
}