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.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<Meeting> getMeetings(String userID)
        throws JsonParseException, JsonMappingException, IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Meetings").appendPath(userID).build().toString();

    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod("GET");
    addRequestHeader(conn, false);//w  w w  .  j  a  v  a2 s .  co m

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

    // Initialize ObjectMapper
    List<Meeting> meetingsList = new ArrayList<Meeting>();
    List<String> meetingIDList = new ArrayList<String>();
    JsonNode responseNode = MAPPER.readTree(response);
    final JsonNode meetingsArray = responseNode.get(Keys.Meeting.LIST);

    if (meetingsArray != null && meetingsArray.isArray()) {
        for (final JsonNode meetingNode : meetingsArray) {
            String _id = meetingNode.get(Keys._ID).asText();
            if (!meetingNode.get("type").asText().equals("MADE_MEETING")) {
                meetingIDList.add(_id);
            }
        }
    } else {
        logError(TAG, responseNode);
    }

    conn.disconnect();
    for (String id : meetingIDList) {
        meetingsList.add(MeetingDatabaseAdapter.getMeetingInfo(id));
    }
    return meetingsList;
}

From source file:com.example.android.tvleanback.data.VideoDbBuilder.java

/**
 * Fetch JSON object from a given URL./*from w  w w  .  j  a  v a 2 s. co m*/
 *
 * @return the JSONObject representation of the response
 * @throws JSONException
 * @throws IOException
 */
private JSONObject fetchJSON(String urlString) throws JSONException, IOException {
    BufferedReader reader = null;
    java.net.URL url = new java.net.URL(urlString);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String json = sb.toString();
        return new JSONObject(json);
    } finally {
        urlConnection.disconnect();
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.e(TAG, "JSON feed closed", e);
            }
        }
    }
}

From source file:it.polito.tellmefirst.web.rest.apimanager.RestManager.java

public String getStringFromAPI(String urlStr) {
    LOG.debug("[getStringFromAPI] - BEGIN");
    String result = "";
    try {//w  ww.j  ava2 s.  c  o  m
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() != 200) {
            System.out.println(conn.getResponseCode() + "***********************************");
            throw new IOException(conn.getResponseMessage());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();
        result = sb.toString();
    } catch (Exception e) {
        LOG.error("[getStringFromAPI] - EXCEPTION: ", e);
    }
    LOG.debug("[getStringFromAPI] - END");
    return result;
}

From source file:org.devnexus.aerogear.HttpRestProvider.java

/**
 * {@inheritDoc}// ww w .j ava  2  s.c  om
 */
@Override
public HeaderAndBody get() throws HttpException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = prepareConnection();
        return getHeaderAndBody(urlConnection);

    } catch (IOException e) {
        Log.e(TAG, "Error on GET of " + url, e);
        throw new RuntimeException(e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.exoplatform.utils.image.ExoPicassoDownloader.java

@Override
public Response load(Uri uri, int networkPolicy) throws IOException {
    // TODO use networkPolicy as in com.squareup.picasso.UrlConnectionDownloader
    // https://github.com/square/picasso/blob/picasso-parent-2.5.2/picasso/src/main/java/com/squareup/picasso/UrlConnectionDownloader.java
    HttpURLConnection connection = connection(uri);
    connection.setInstanceFollowRedirects(true);
    connection.setUseCaches(true);/*from w w  w.  j  av a  2s  .  c om*/

    int responseCode = connection.getResponseCode();
    // Handle HTTP redirections that are not managed by HttpURLConnection
    // automatically, e.g. HTTP -> HTTPS
    // TODO consider using OkHttp instead
    if (responseCode >= 300 && responseCode < 400) {
        String location = connection.getHeaderField("Location");
        connection.disconnect();
        connection = connection(Uri.parse(location));
        connection.setInstanceFollowRedirects(true);
        connection.setUseCaches(true);
        responseCode = connection.getResponseCode();
    }
    // Either the original or the new request have failed -> error
    if (responseCode >= 300) {
        connection.disconnect();
        throw new ResponseException(responseCode + " " + connection.getResponseMessage(), networkPolicy,
                responseCode);
    }

    long contentLength = connection.getHeaderFieldInt("Content-Length", -1);
    // boolean fromCache =
    // parseResponseSourceHeader(connection.getHeaderField(RESPONSE_SOURCE));
    boolean fromCache = false;

    return new Response(connection.getInputStream(), fromCache, contentLength);
}

From source file:org.softcatala.traductor.ServerTranslation.java

protected String sendJson(final String langCode, final String text) {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit 
    HttpURLConnection uc = null;

    try {//w ww  . j av a 2  s. co m
        String url = BuildURL(langCode, text);
        uc = (HttpURLConnection) new URL(url).openConnection();

        InputStream is = uc.getInputStream();
        String result = toString(is);
        JSONObject json = new JSONObject(result);
        return ((JSONObject) json.get("responseData")).getString("translatedText");
    } catch (Exception e) {
        String msg = _context.getString(R.string.ServerError);
        if (uc != null) {
            uc.disconnect();
        }

        String exceptionMessage = "";

        if (e instanceof UnknownHostException) {
            exceptionMessage = _context.getString(R.string.UnkownHostExceptionMessage);
        } else {
            exceptionMessage = e.toString();
        }

        return String.format(msg, exceptionMessage);
    }
}

From source file:com.wisc.cs407project.ImageLoader.ImageLoader.java

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);
    Bitmap b = decodeFile(f);/*from   w ww  .ja v  a  2 s . c  o m*/

    //from Local Directory
    BufferedReader in = null;
    UrlValidator validator = new UrlValidator();
    if (new File(url).exists()) {
        b = decodeFile(new File(url));
        if (b != null)
            return b;
    }

    //from web
    try {
        //check SD cache first
        if (b != null)
            return b;

        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is = conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        conn.disconnect();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if (ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

private InputStream getIS(int addr, boolean online) throws IOException {
    if (!online || LOCAL_DEFINITION_TESTING) {
        if (addr == URL_VERSION_ID) {
            return getResources().getAssets().open(URL_VERSION);
        } else if (addr == URL_TICKETS_ID) {
            return getResources().getAssets().open(URL_TICKETS);
        } else {//from   www  . j a v  a 2 s  .  co m
            throw new IOException("requested addr " + addr + " not found");
        }
    } else {
        URL url;

        if (addr == URL_VERSION_ID) {
            url = new URL(Constants.DATA_URL_BASE + URL_VERSION);
        } else if (addr == URL_TICKETS_ID) {
            url = new URL(Constants.DATA_URL_BASE + URL_TICKETS);
        } else {
            throw new IOException("requested addr " + addr + " not found");
        }

        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(30000);
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(false);

            if (connection.getResponseCode() != 200) {
                connection.disconnect();

                throw new IOException("status " + connection.getResponseCode() + " received");
            }

            if (addr == URL_VERSION_ID) {
                DebugLog.i("Downloading definition version info...");
            } else if (addr == URL_TICKETS_ID) {
                DebugLog.i("Downloading new tickets definition...");
            }

            return connection.getInputStream();
        } catch (SecurityException e) {
            throw new IOException("Internet access denied");
        }
    }
}

From source file:com.atinternet.tracker.TVTrackingPlugin.java

@Override
protected void execute(Tracker tracker) {
    this.tracker = tracker;
    try {//  w w w.j  ava  2  s.  c om
        if (sessionIsExpired()) {
            setDirectCampaignToRemanent();

            URL url = new URL(tracker.TVTracking().getCampaignURL());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(TIMEOUT);
            connection.setConnectTimeout(TIMEOUT);
            connection.setDoInput(true);
            connection.connect();
            response = getTvTrackingResponse(stringifyTvTResponse(connection), connection);
            connection.disconnect();
        } else {
            response = getTvTrackingResponse(
                    Tracker.getPreferences().getString(TrackerConfigurationKeys.DIRECT_CAMPAIGN_SAVED, null),
                    null);
        }
        Tool.executeCallback(tracker.getListener(), Tool.CallbackType.partner, "TV Tracking : " + response);
        Tracker.getPreferences().edit()
                .putLong(TrackerConfigurationKeys.LAST_TVT_EXECUTE_TIME, System.currentTimeMillis()).apply();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

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

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

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

        //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();
        }
    }

}