Example usage for java.net HttpURLConnection getLastModified

List of usage examples for java.net HttpURLConnection getLastModified

Introduction

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

Prototype

public long getLastModified() 

Source Link

Document

Returns the value of the last-modified header field.

Usage

From source file:at.spardat.xma.boot.transport.HTTPTransport.java

private Result getResourceImpl(IRtXMASessionClient session, URL url, long modifiedSince, String etag)
        throws CommunicationException {

    /* locals ---------------------------------- */
    Result result = new Result();
    int code = 0;
    HttpURLConnection conn;
    /* locals ---------------------------------- */

    try {//ww w  .  j a va  2s.  co  m
        conn = (HttpURLConnection) url.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
        }
        sendCookies(session, url, conn);
        if (etag != null) {
            conn.setRequestProperty("If-None-Match", etag); //$NON-NLS-1$
        }

        String strUrl = url.toExternalForm();
        if (url.getQuery() == null && (strUrl.endsWith(".jar") || strUrl.endsWith(".xml"))) {
            conn.setRequestProperty(Statics.HTTP_CACHE_CONTROL, Statics.HTTP_MAX_AGE + "=0"); //$NON-NLS-1$
        }

        if (modifiedSince > 0) {
            // see sun bugid: 4397096
            // if HTTP_Util library is used, the original method may also be used.
            // conn.setIfModifiedSince(modifiedSince);
            conn.setRequestProperty(Statics.strIfModifiedSince, HTTPTransport.httpDate(modifiedSince));
        }
        conn.setRequestProperty(Statics.HTTP_ACCEPT, "*/*"); //$NON-NLS-1$
        conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME);

    } catch (IOException exc) {
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' form server:", exc); //$NON-NLS-1$
        throw new ConnectException("error loading '" + url.toString() + "' form server:", exc);
    }

    try {
        code = conn.getResponseCode();
        if (code == HttpURLConnection.HTTP_NOT_MODIFIED) {
            result.contentLength_ = 0;
            result.lastModified_ = conn.getLastModified();
            if (result.lastModified_ <= 0) {
                result.lastModified_ = modifiedSince;
            }
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            if (result.etag_ == null) {
                result.etag_ = etag;
            }
            log_.log(LogLevel.FINE, "resource not modified: {0}", url.toExternalForm()); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_OK) {
            result.contentLength_ = conn.getContentLength();
            result.lastModified_ = conn.getLastModified();
            result.expirationDate_ = conn.getExpiration();
            result.etag_ = conn.getHeaderField(Statics.strEtag);
            result.transformations_ = conn.getHeaderField(Statics.TRANSFORM_HEADER);

            result.setBuffer(this.readOutput(conn));

            if (result.contentLength_ < 0) {
                result.contentLength_ = result.buffer_.length;
            }
        } else if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM) {
            String location = conn.getHeaderField(Statics.HTTP_LOCATION);
            throw new RedirectException("redirect received from " + url.toString() + " to " + location, code,
                    location);
        } else {
            if (code < 500)
                throw new ConnectException("error loading '" + url.toString() + "' from the server:", code);
            else
                throw new ServerException("error loading '" + url.toString() + "' from the server:", code);
        }
        readCookies(session, url, conn);
    } catch (RedirectException re) {
        throw re;
    } catch (CommunicationException ce) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ce); //$NON-NLS-1$
        throw ce;
    } catch (Exception ex) {
        if (code != 0)
            log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$
        log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ex); //$NON-NLS-1$
        if (code < 500)
            throw new ConnectException("error loading '" + url.toString() + "' from the server:", ex);
        else
            throw new ServerException("error loading '" + url.toString() + "' from the server:", ex);
    }

    return result;
}

From source file:com.sonaive.v2ex.ui.debug.RSSPullService.java

/**
 * In an IntentService, onHandleIntent is run on a background thread.  As it
 * runs, it broadcasts its current status using the LocalBroadcastManager.
 * @param workIntent The Intent that starts the IntentService. This Intent contains the
 * URL of the web site from which the RSS parser gets data.
 *//*from   ww  w  . j  ava 2 s.  co  m*/
@Override
protected void onHandleIntent(Intent workIntent) {

    BroadcastNotifier mBroadcaster = new BroadcastNotifier(this);
    // Gets a URL to read from the incoming Intent's "data" value
    String localUrlString = workIntent.getDataString();

    // Creates a projection to use in querying the modification date table in the provider.
    final String[] dateProjection = new String[] { ModiDates._ID, ModiDates.MODI_DATE };

    // A URL that's local to this method
    URL localURL;

    // A cursor that's local to this method.
    Cursor cursor = null;

    /*
     * A block that tries to connect to the Picasa featured picture URL passed as the "data"
     * value in the incoming Intent. The block throws exceptions (see the end of the block).
     */
    try {

        // Convert the incoming data string to a URL.
        localURL = new URL(localUrlString);

        /*
         * Tries to open a connection to the URL. If an IO error occurs, this throws an
         * IOException
         */
        URLConnection localURLConnection = localURL.openConnection();

        // If the connection is an HTTP connection, continue
        if ((localURLConnection instanceof HttpURLConnection)) {

            // Broadcasts an Intent indicating that processing has started.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

            // Casts the connection to a HTTP connection
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

            // Sets the user agent for this request.
            localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);

            /*
             * Queries the content provider to see if this URL was read previously, and when.
             * The content provider throws an exception if the URI is invalid.
             */
            cursor = getContentResolver().query(ModiDates.CONTENT_URI, dateProjection, null, null, null);

            // Flag to indicate that new metadata was retrieved
            boolean newMetadataRetrieved;

            /*
             * Tests to see if the table contains a modification date for the URL
             */
            if (null != cursor && cursor.moveToFirst()) {

                long storedModifiedDate = cursor.getLong(cursor.getColumnIndex(ModiDates.MODI_DATE));

                /*
                 * If the modified date isn't 0, sets another request property to ensure that
                 * data is only downloaded if it has changed since the last recorded
                 * modification date. Formats the date according to the RFC1123 format.
                 */
                if (0 != storedModifiedDate) {
                    localHttpURLConnection.setRequestProperty("If-Modified-Since",
                            org.apache.http.impl.cookie.DateUtils.formatDate(new Date(storedModifiedDate),
                                    org.apache.http.impl.cookie.DateUtils.PATTERN_RFC1123));
                }

                // Marks that new metadata does not need to be retrieved
                newMetadataRetrieved = false;

            } else {

                /*
                 * No modification date was found for the URL, so newmetadata has to be
                 * retrieved.
                 */
                newMetadataRetrieved = true;

            }

            // Reports that the service is about to connect to the RSS feed
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

            // Gets a response code from the RSS server
            int responseCode = localHttpURLConnection.getResponseCode();

            switch (responseCode) {

            // If the response is OK
            case HttpStatus.SC_OK:

                // Gets the last modified data for the URL
                long lastModifiedDate = localHttpURLConnection.getLastModified();

                // Reports that the service is parsing
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_PARSING);

                /*
                 * Instantiates a pull parser and uses it to parse XML from the RSS feed.
                 * The mBroadcaster argument send a broadcaster utility object to the
                 * parser.
                 */
                RSSPullParser localPicasaPullParser = new RSSPullParser();

                localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);

                // Reports that the service is now writing data to the content provider.
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_WRITING);

                // Gets image data from the parser
                Vector<ContentValues> imageValues = localPicasaPullParser.getImages();

                // Stores the number of images
                int imageVectorSize = imageValues.size();

                // Creates one ContentValues for each image
                ContentValues[] imageValuesArray = new ContentValues[imageVectorSize];

                imageValuesArray = imageValues.toArray(imageValuesArray);

                /*
                 * Stores the image data in the content provider. The content provider
                 * throws an exception if the URI is invalid.
                 */
                getContentResolver().bulkInsert(PicasaImages.CONTENT_URI, imageValuesArray);

                // Creates another ContentValues for storing date information
                ContentValues dateValues = new ContentValues();

                // Adds the URL's last modified date to the ContentValues
                dateValues.put(ModiDates.MODI_DATE, lastModifiedDate);

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(ModiDates.CONTENT_URI, dateValues);
                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(ModiDates.CONTENT_URI, dateValues,
                            ModiDates._ID + "=" + cursor.getString(cursor.getColumnIndex(ModiDates._ID)), null);
                }
                break;

            }

            // Reports that the feed retrieval is complete.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
        }

        // Handles possible exceptions
    } catch (MalformedURLException localMalformedURLException) {

        localMalformedURLException.printStackTrace();

    } catch (IOException localIOException) {

        localIOException.printStackTrace();

    } catch (XmlPullParserException localXmlPullParserException) {

        localXmlPullParserException.printStackTrace();

    } finally {

        // If an exception occurred, close the cursor to prevent memory leaks.
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param urlConn/*ww  w  . j a v a2 s  .com*/
 * @param responseCode
 * @param exception
 * @throws DAOException
 */
private void addSourceMetadata(HttpURLConnection urlConn, int responseCode, String responseMessage,
        Exception exception) {

    String firstSeen = formatDate(getContextSourceDTO().getTimeCreated());
    String lastRefreshed = formatDate(new Date());

    addSourceMetadata(Predicates.CR_FIRST_SEEN, ObjectDTO.createLiteral(firstSeen, XMLSchema.DATETIME));
    addSourceMetadata(Predicates.CR_LAST_REFRESHED, ObjectDTO.createLiteral(lastRefreshed, XMLSchema.DATETIME));

    if (isError(responseCode)) {
        if (responseMessage == null) {
            responseMessage = "";
        }
        addSourceMetadata(Predicates.CR_ERROR_MESSAGE, ObjectDTO.createLiteral(
                "Server returned error: " + responseMessage + " (HTTP response code: " + responseCode + ")"));
    } else if (exception != null) {
        addSourceMetadata(Predicates.CR_ERROR_MESSAGE, ObjectDTO.createLiteral(exception.toString()));
    }

    if (urlConn != null) {

        // content type
        String contentType = getSourceContentType(urlConn);
        if (!StringUtils.isBlank(contentType)) {

            addSourceMetadata(Predicates.CR_MEDIA_TYPE, ObjectDTO.createLiteral(contentType));

            // if content type is not "application/rdf+xml", generate rdf:type from the
            // DublinCore type mappings
            if (!contentType.toLowerCase().startsWith("application/rdf+xml")) {

                String rdfType = MediaTypeToDcmiTypeConverter.getDcmiTypeFor(contentType);
                if (rdfType != null) {
                    addSourceMetadata(Predicates.RDF_TYPE, ObjectDTO.createResource(rdfType));
                }
            }
        }

        // content's last modification
        long contentLastModified = urlConn.getLastModified();
        if (contentLastModified > 0) {
            String lastModifString = formatDate(new Date(contentLastModified));
            addSourceMetadata(Predicates.CR_LAST_MODIFIED,
                    ObjectDTO.createLiteral(lastModifString, XMLSchema.DATETIME));
        }

        // content size
        int contentLength = urlConn.getContentLength();
        if (contentLength >= 0) {
            addSourceMetadata(Predicates.CR_BYTE_SIZE, ObjectDTO.createLiteral(contentLength));
        }
    }

}

From source file:xiaofans.threadsample.RSSPullService.java

/**
 * In an IntentService, onHandleIntent is run on a background thread.  As it
 * runs, it broadcasts its current status using the LocalBroadcastManager.
 * @param workIntent The Intent that starts the IntentService. This Intent contains the
 * URL of the web site from which the RSS parser gets data.
 */// w  ww  .j  a v  a2 s .  c o m
@Override
protected void onHandleIntent(Intent workIntent) {
    // Gets a URL to read from the incoming Intent's "data" value
    String localUrlString = workIntent.getDataString();

    // Creates a projection to use in querying the modification date table in the provider.
    final String[] dateProjection = new String[] { DataProviderContract.ROW_ID,
            DataProviderContract.DATA_DATE_COLUMN };

    // A URL that's local to this method
    URL localURL;

    // A cursor that's local to this method.
    Cursor cursor = null;

    /*
     * A block that tries to connect to the Picasa featured picture URL passed as the "data"
     * value in the incoming Intent. The block throws exceptions (see the end of the block).
     */
    try {

        // Convert the incoming data string to a URL.
        localURL = new URL(localUrlString);

        /*
         * Tries to open a connection to the URL. If an IO error occurs, this throws an
         * IOException
         */
        URLConnection localURLConnection = localURL.openConnection();

        // If the connection is an HTTP connection, continue
        if ((localURLConnection instanceof HttpURLConnection)) {

            // Broadcasts an Intent indicating that processing has started.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

            // Casts the connection to a HTTP connection
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

            // Sets the user agent for this request.
            localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);

            /*
             * Queries the content provider to see if this URL was read previously, and when.
             * The content provider throws an exception if the URI is invalid.
             */
            cursor = getContentResolver().query(DataProviderContract.DATE_TABLE_CONTENTURI, dateProjection,
                    null, null, null);

            // Flag to indicate that new metadata was retrieved
            boolean newMetadataRetrieved;

            /*
             * Tests to see if the table contains a modification date for the URL
             */
            if (null != cursor && cursor.moveToFirst()) {

                // Find the URL's last modified date in the content provider
                long storedModifiedDate = cursor
                        .getLong(cursor.getColumnIndex(DataProviderContract.DATA_DATE_COLUMN));

                /*
                 * If the modified date isn't 0, sets another request property to ensure that
                 * data is only downloaded if it has changed since the last recorded
                 * modification date. Formats the date according to the RFC1123 format.
                 */
                if (0 != storedModifiedDate) {
                    localHttpURLConnection.setRequestProperty("If-Modified-Since",
                            org.apache.http.impl.cookie.DateUtils.formatDate(new Date(storedModifiedDate),
                                    org.apache.http.impl.cookie.DateUtils.PATTERN_RFC1123));
                }

                // Marks that new metadata does not need to be retrieved
                newMetadataRetrieved = false;

            } else {

                /*
                 * No modification date was found for the URL, so newmetadata has to be
                 * retrieved.
                 */
                newMetadataRetrieved = true;

            }

            // Reports that the service is about to connect to the RSS feed
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

            // Gets a response code from the RSS server
            int responseCode = localHttpURLConnection.getResponseCode();

            switch (responseCode) {

            // If the response is OK
            case HttpStatus.SC_OK:

                // Gets the last modified data for the URL
                long lastModifiedDate = localHttpURLConnection.getLastModified();

                // Reports that the service is parsing
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_PARSING);

                /*
                 * Instantiates a pull parser and uses it to parse XML from the RSS feed.
                 * The mBroadcaster argument send a broadcaster utility object to the
                 * parser.
                 */
                RSSPullParser localPicasaPullParser = new RSSPullParser();

                localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);

                // Reports that the service is now writing data to the content provider.
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_WRITING);

                // Gets image data from the parser
                Vector<ContentValues> imageValues = localPicasaPullParser.getImages();

                // Stores the number of images
                int imageVectorSize = imageValues.size();

                // Creates one ContentValues for each image
                ContentValues[] imageValuesArray = new ContentValues[imageVectorSize];

                imageValuesArray = imageValues.toArray(imageValuesArray);

                /*
                 * Stores the image data in the content provider. The content provider
                 * throws an exception if the URI is invalid.
                 */
                getContentResolver().bulkInsert(DataProviderContract.PICTUREURL_TABLE_CONTENTURI,
                        imageValuesArray);

                // Creates another ContentValues for storing date information
                ContentValues dateValues = new ContentValues();

                // Adds the URL's last modified date to the ContentValues
                dateValues.put(DataProviderContract.DATA_DATE_COLUMN, lastModifiedDate);

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues);

                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues,
                            DataProviderContract.ROW_ID + "="
                                    + cursor.getString(cursor.getColumnIndex(DataProviderContract.ROW_ID)),
                            null);
                }
                break;

            }

            // Reports that the feed retrieval is complete.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
        }

        // Handles possible exceptions
    } catch (MalformedURLException localMalformedURLException) {

        localMalformedURLException.printStackTrace();

    } catch (IOException localIOException) {

        localIOException.printStackTrace();

    } catch (XmlPullParserException localXmlPullParserException) {

        localXmlPullParserException.printStackTrace();

    } finally {

        // If an exception occurred, close the cursor to prevent memory leaks.
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:com.example.android.threadsample.RSSPullService.java

/**
 * In an IntentService, onHandleIntent is run on a background thread.  As it
 * runs, it broadcasts its current status using the LocalBroadcastManager.
 * @param workIntent The Intent that starts the IntentService. This Intent contains the
 * URL of the web site from which the RSS parser gets data.
 *//*from   w  w w .  j  av a  2 s  .com*/
@Override
protected void onHandleIntent(Intent workIntent) {
    // Gets a URL to read from the incoming Intent's "data" value
    String localUrlString = workIntent.getDataString();

    // Creates a projection to use in querying the modification date table in the provider.
    final String[] dateProjection = new String[] { DataProviderContract.ROW_ID,
            DataProviderContract.DATA_DATE_COLUMN };

    // A URL that's local to this method
    URL localURL;

    // A cursor that's local to this method.
    Cursor cursor = null;

    /*
     * A block that tries to connect to the Picasa featured picture URL passed as the "data"
     * value in the incoming Intent. The block throws exceptions (see the end of the block).
     */
    try {

        // Convert the incoming data string to a URL.
        localURL = new URL(localUrlString);

        /*
         * Tries to open a connection to the URL. If an IO error occurs, this throws an
         * IOException
         */
        URLConnection localURLConnection = localURL.openConnection();

        // If the connection is an HTTP connection, continue
        if ((localURLConnection instanceof HttpURLConnection)) {

            // Broadcasts an Intent indicating that processing has started.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED);

            // Casts the connection to a HTTP connection
            HttpURLConnection localHttpURLConnection = (HttpURLConnection) localURLConnection;

            // Sets the user agent for this request.
            localHttpURLConnection.setRequestProperty("User-Agent", Constants.USER_AGENT);

            /*
             * Queries the content provider to see if this URL was read previously, and when.
             * The content provider throws an exception if the URI is invalid.
             */
            cursor = getContentResolver().query(DataProviderContract.DATE_TABLE_CONTENTURI, dateProjection,
                    null, null, null);

            // Flag to indicate that new metadata was retrieved
            boolean newMetadataRetrieved;

            /*
             * Tests to see if the table contains a modification date for the URL
             */
            if (null != cursor && cursor.moveToFirst()) {

                // Find the URL's last modified date in the content provider
                long storedModifiedDate = cursor
                        .getLong(cursor.getColumnIndex(DataProviderContract.DATA_DATE_COLUMN));

                /*
                 * If the modified date isn't 0, sets another request property to ensure that
                 * data is only downloaded if it has changed since the last recorded
                 * modification date. Formats the date according to the RFC1123 format.
                 */
                if (0 != storedModifiedDate) {
                    localHttpURLConnection.setRequestProperty("If-Modified-Since",
                            org.apache.http.impl.cookie.DateUtils.formatDate(new Date(storedModifiedDate),
                                    org.apache.http.impl.cookie.DateUtils.PATTERN_RFC1123));
                }

                // Marks that new metadata does not need to be retrieved
                newMetadataRetrieved = false;

            } else {

                /*
                 * No modification date was found for the URL, so newmetadata has to be
                 * retrieved.
                 */
                newMetadataRetrieved = true;

            }

            // Reports that the service is about to connect to the RSS feed
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_CONNECTING);

            // Gets a response code from the RSS server
            int responseCode = localHttpURLConnection.getResponseCode();

            switch (responseCode) {

            // If the response is OK
            case HttpStatus.SC_OK:

                // Gets the last modified data for the URL
                long lastModifiedDate = localHttpURLConnection.getLastModified();

                // Reports that the service is parsing
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_PARSING);

                /*
                 * Instantiates a pull parser and uses it to parse XML from the RSS feed.
                 * The mBroadcaster argument send a broadcaster utility object to the
                 * parser.
                 */
                RSSPullParser localPicasaPullParser = new RSSPullParser();

                try {
                    localPicasaPullParser.parseXml(localURLConnection.getInputStream(), mBroadcaster);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // Reports that the service is now writing data to the content provider.
                mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_WRITING);

                // Gets image data from the parser
                Vector<ContentValues> imageValues = localPicasaPullParser.getImages();

                // Stores the number of images
                int imageVectorSize = imageValues.size();

                // Creates one ContentValues for each image
                ContentValues[] imageValuesArray = new ContentValues[imageVectorSize];

                imageValuesArray = imageValues.toArray(imageValuesArray);

                /*
                 * Stores the image data in the content provider. The content provider
                 * throws an exception if the URI is invalid.
                 */
                getContentResolver().bulkInsert(DataProviderContract.PICTUREURL_TABLE_CONTENTURI,
                        imageValuesArray);

                // Creates another ContentValues for storing date information
                ContentValues dateValues = new ContentValues();

                // Adds the URL's last modified date to the ContentValues
                dateValues.put(DataProviderContract.DATA_DATE_COLUMN, lastModifiedDate);

                if (newMetadataRetrieved) {

                    // No previous metadata existed, so insert the data
                    getContentResolver().insert(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues);

                } else {

                    // Previous metadata existed, so update it.
                    getContentResolver().update(DataProviderContract.DATE_TABLE_CONTENTURI, dateValues,
                            DataProviderContract.ROW_ID + "="
                                    + cursor.getString(cursor.getColumnIndex(DataProviderContract.ROW_ID)),
                            null);
                }
                break;

            }

            // Reports that the feed retrieval is complete.
            mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE);
        }

        // Handles possible exceptions
    } catch (MalformedURLException localMalformedURLException) {

        localMalformedURLException.printStackTrace();

    } catch (IOException localIOException) {

        localIOException.printStackTrace();

    } catch (XmlPullParserException localXmlPullParserException) {

        localXmlPullParserException.printStackTrace();

    } finally {

        // If an exception occurred, close the cursor to prevent memory leaks.
        if (null != cursor) {
            cursor.close();
        }
    }
}

From source file:edu.mit.mobile.android.net.DownloadLoader.java

@Override
public Uri loadInBackground() {
    boolean alreadyHasDownload = false;

    if (!outdir.exists() && !outdir.mkdirs()) {
        mException = new IOException("could not mkdirs: " + outdir.getAbsolutePath());
        return null;
    }/* w  w w  .ja va2  s .  c o m*/
    final String fname = mUrl.substring(mUrl.lastIndexOf('/'));
    final File outfile = new File(outdir, fname);

    alreadyHasDownload = outfile.exists() && outfile.length() > MINIMUM_REASONABLE_VIDEO_SIZE;

    final long lastModified = outfile.exists() ? outfile.lastModified() : 0;

    try {
        final NetworkInfo netInfo = mCm.getActiveNetworkInfo();
        if (netInfo == null || !netInfo.isConnected()) {
            // no connection, but there's already a file. Hopefully it works!
            if (alreadyHasDownload) {
                return Uri.fromFile(outfile);
            } else {
                mException = new IOException(getContext().getString(R.string.err_no_data_connection));
                return null;
            }
        }

        HttpURLConnection hc = (HttpURLConnection) new URL(mUrl).openConnection();

        hc.setInstanceFollowRedirects(true);

        if (lastModified != 0) {
            hc.setIfModifiedSince(lastModified);
        }

        int resp = hc.getResponseCode();

        if (resp >= 300 && resp < 400) {

            final String redirectUrl = hc.getURL().toExternalForm();

            if (BuildConfig.DEBUG) {
                Log.d(TAG, "following redirect to " + redirectUrl);
            }
            hc = (HttpURLConnection) new URL(redirectUrl).openConnection();

            if (lastModified != 0) {
                hc.setIfModifiedSince(lastModified);
            }
            resp = hc.getResponseCode();
        }

        if (resp != HttpStatus.SC_OK && resp != HttpStatus.SC_NOT_MODIFIED) {
            Log.e(TAG, "got a non-200 response from server");
            mException = new NetworkProtocolException("Received " + resp + " response from server");
            return null;
        }
        if (resp == HttpStatus.SC_NOT_MODIFIED) {
            if (Constants.DEBUG) {
                Log.d(TAG, "got NOT MODIFIED");
            }
            // verify the integrity of the file
            if (alreadyHasDownload) {
                if (Constants.DEBUG) {
                    Log.d(TAG, fname + " has not been modified since it was downloaded last");
                }
                return Uri.fromFile(outfile);
            } else {
                // re-request without the if-modified header. This shouldn't happen.
                hc = (HttpURLConnection) new URL(mUrl).openConnection();
                final int responseCode = hc.getResponseCode();
                if (responseCode != HttpStatus.SC_OK) {
                    Log.e(TAG, "got a non-200 response from server");
                    mException = new NetworkProtocolException(
                            "Received " + responseCode + " response from server");
                    return null;
                }
            }
        }

        final int contentLength = hc.getContentLength();

        if (contentLength == 0) {
            Log.e(TAG, "got an empty response from server");
            mException = new IOException("Received an empty response from server.");
            return null;

        } else if (contentLength < MINIMUM_REASONABLE_VIDEO_SIZE) { // this is probably not a
                                                                    // video
            Log.e(TAG, "got a very small response from server of length " + hc.getContentLength());
            mException = new IOException("Received an unusually-small response from server.");
            return null;
        }
        boolean downloadSucceeded = false;
        try {

            final BufferedInputStream bis = new BufferedInputStream(hc.getInputStream());
            final FileOutputStream fos = new FileOutputStream(outfile);
            if (Constants.DEBUG) {
                Log.d(TAG, "downloading...");
            }
            StreamUtils.inputStreamToOutputStream(bis, fos);

            fos.close();

            // store the server's last modified date in the filesystem
            outfile.setLastModified(hc.getLastModified());

            downloadSucceeded = true;
            if (Constants.DEBUG) {
                Log.d(TAG, "done! Saved to " + outfile);
            }
            return Uri.fromFile(outfile);

        } finally {
            hc.disconnect();
            // cleanup if this is the first attempt to download
            if (!alreadyHasDownload && !downloadSucceeded) {
                outfile.delete();
            }
        }
    } catch (final IOException e) {
        Log.e(TAG, "error downloading file", e);
        mException = e;
        return null;
    }
}

From source file:com.cr_wd.android.network.HttpClient.java

/**
 * Performs a HTTP GET/POST Request/* ww w.ja v  a2 s  .  co m*/
 * 
 * @return id of the request
 */
protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params,
        final HttpHandler handler) {
    if (headers == null) {
        headers = new HttpHeaders();
    }
    if (params == null) {
        params = new HttpParams();
    }

    handler.client = this;

    final int requestId = incrementRequestId();

    class HandlerRunnable extends Handler implements Runnable {

        private final Method method;
        private String url;
        private final HttpHeaders headers;
        private final HttpParams params;
        private final HttpHandler handler;
        private HttpResponse response;

        private boolean canceled = false;
        private int retries = 0;

        protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers,
                final HttpParams params, final HttpHandler handler) {
            this.method = method;
            this.url = url;
            this.headers = headers;
            this.params = params;
            this.handler = handler;
        }

        @Override
        public void run() {
            execute();
        }

        private void execute() {
            response = new HttpResponse(requestId, method, url);

            HttpURLConnection conn = null;
            try {
                /* append query string for GET requests */
                if (method == Method.GET) {
                    if (!params.urlParams.isEmpty()) {
                        url += ('?' + params.getParamString());
                    }
                }

                /* setup headers for POST requests */
                if (method == Method.POST) {
                    headers.addHeader("Accept-Charset", requestOptions.encoding);
                    if (params.hasMultipartParams()) {
                        final SimpleMultipart multipart = params.getMultipart();
                        headers.addHeader("Content-Type", multipart.getContentType());
                    } else {
                        headers.addHeader("Content-Type",
                                "application/x-www-form-urlencoded;charset=" + requestOptions.encoding);
                    }
                }

                if (canceled) {
                    postCancel();
                    return;
                }

                /* open and configure the connection */
                conn = (HttpURLConnection) new URL(url).openConnection();

                postStart();

                if (method == Method.GET) {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                } else if (method == Method.POST) {
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setUseCaches(false);
                }
                conn.setAllowUserInteraction(false);
                conn.setReadTimeout(requestOptions.readTimeout);
                conn.setConnectTimeout(requestOptions.connectTimeout);

                /* add headers to the connection */
                for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
                    for (final String value : entry.getValue()) {
                        conn.addRequestProperty(entry.getKey(), value);
                    }
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.requestProperties = conn.getRequestProperties();

                /* do post */
                if (method == Method.POST) {
                    InputStream is;

                    if (params.hasMultipartParams()) {
                        is = params.getMultipart().getContent();
                    } else {
                        is = new ByteArrayInputStream(params.getParamString().getBytes());
                    }

                    final OutputStream os = conn.getOutputStream();

                    writeStream(os, is);
                } else {
                    conn.connect();
                }

                if (canceled) {
                    try {
                        conn.disconnect();
                    } catch (final Exception e) {
                    }
                    postCancel();
                    return;
                }

                response.contentEncoding = conn.getContentEncoding();
                response.contentLength = conn.getContentLength();
                response.contentType = conn.getContentType();
                response.date = conn.getDate();
                response.expiration = conn.getExpiration();
                response.headerFields = conn.getHeaderFields();
                response.ifModifiedSince = conn.getIfModifiedSince();
                response.lastModified = conn.getLastModified();
                response.responseCode = conn.getResponseCode();
                response.responseMessage = conn.getResponseMessage();

                /* do get */
                if (conn.getResponseCode() < 400) {
                    response.responseBody = readStream(conn.getInputStream());
                    postSuccess();
                } else {
                    response.responseBody = readStream(conn.getErrorStream());
                    response.throwable = new Exception(response.responseMessage);
                    postError();
                }

            } catch (final Exception e) {
                if (retries < requestOptions.maxRetries) {
                    retries++;
                    postRetry();
                    execute();
                } else {
                    response.responseBody = e.getMessage();
                    response.throwable = e;
                    postError();
                }
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }

        private String readStream(final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            final ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                baf.append(buffer, 0, read);
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }

            return new String(baf.toByteArray());
        }

        private void writeStream(final OutputStream os, final InputStream is) throws IOException {
            final BufferedInputStream bis = new BufferedInputStream(is);
            int read = 0;
            final byte[] buffer = new byte[8192];
            while (true) {
                if (canceled) {
                    break;
                }

                read = bis.read(buffer);
                if (read == -1) {
                    break;
                }
                os.write(buffer, 0, read);
            }

            if (!canceled) {
                os.flush();
            }

            try {
                os.close();
            } catch (final IOException e) {
            }

            try {
                bis.close();
            } catch (final IOException e) {
            }

            try {
                is.close();
            } catch (final IOException e) {
            }
        }

        @Override
        public void handleMessage(final Message msg) {
            if (msg.what == HttpHandler.MESSAGE_CANCEL) {
                canceled = true;
            }
        }

        private void postSuccess() {
            postMessage(HttpHandler.MESSAGE_SUCCESS);
        }

        private void postError() {
            postMessage(HttpHandler.MESSAGE_ERROR);
        }

        private void postCancel() {
            postMessage(HttpHandler.MESSAGE_CANCEL);
        }

        private void postStart() {
            postMessage(HttpHandler.MESSAGE_START);
        }

        private void postRetry() {
            postMessage(HttpHandler.MESSAGE_RETRY);
        }

        private void postMessage(final int what) {
            final Message msg = handler.obtainMessage();
            msg.what = what;
            msg.arg1 = requestId;
            msg.obj = response;
            handler.sendMessage(msg);
        }
    }
    ;
    /* Create a new HandlerRunnable and start it */
    final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler);
    requests.put(requestId, new WeakReference<Handler>(hr));
    new Thread(hr).start();

    /* Return with the request id */
    return requestId;
}