Example usage for java.net HttpURLConnection getURL

List of usage examples for java.net HttpURLConnection getURL

Introduction

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

Prototype

public URL getURL() 

Source Link

Document

Returns the value of this URLConnection 's URL field.

Usage

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Check for updates to the bus stop database. This may happen automatically
 * if 24 hours have elapsed since the last check, or if the user has forced
 * the action. If a database update is found, then the new database is
 * downloaded and placed in the correct location.
 * //from  w  w  w  . j av a  2 s  .  c  o m
 * @param context The context.
 * @param force True if the user forced the check, false if not.
 */
public static void checkForDBUpdates(final Context context, final boolean force) {
    // Check to see if the user wants their database automatically updated.
    final SharedPreferences sp = context.getSharedPreferences(PreferencesActivity.PREF_FILE, 0);
    final boolean autoUpdate = sp.getBoolean(PREF_DATABASE_AUTO_UPDATE, true);
    final SharedPreferences.Editor edit = sp.edit();

    // Continue to check if the user has enabled it, or a check has been
    // forced (from the Preferences).
    if (autoUpdate || force) {
        if (!force) {
            // If it has not been forced, check the last update time. It is
            // only checked once per day. Abort if it is too soon.
            long lastCheck = sp.getLong("lastUpdateCheck", 0);
            if ((System.currentTimeMillis() - lastCheck) < 86400000)
                return;
        }

        // Construct the checking URL.
        final StringBuilder sb = new StringBuilder();
        sb.append(DB_API_CHECK_URL);
        sb.append(ApiKey.getHashedKey());
        sb.append("&random=");
        // A random number is used so networks don't cache the HTTP
        // response.
        sb.append(random.nextInt());
        try {
            // Do connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                // Read the incoming data.
                int data;
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String topoId;
        try {
            // Parse the JSON and get the topoId from it.
            final JSONObject jo = new JSONObject(sb.toString());
            topoId = jo.getString("topoId");
        } catch (JSONException e) {
            return;
        }

        // If there's topoId then it cannot continue.
        if (topoId == null || topoId.length() == 0)
            return;

        // Get the current topoId from the database.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        final String dbTopoId = bsd.getTopoId();

        // If the topoIds match, write our check time to SharedPreferences.
        if (topoId.equals(dbTopoId)) {
            edit.putLong("lastUpdateCheck", System.currentTimeMillis());
            edit.commit();
            if (force) {
                // It was forced, alert the user there is no update
                // available.
                Looper.prepare();
                Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
            return;
        }

        // There is an update available. Empty the StringBuilder then create
        // the URL to get the new database information.
        sb.setLength(0);
        sb.append(DB_UPDATE_CHECK_URL);
        sb.append(random.nextInt());
        sb.append("&key=");
        sb.append(ApiKey.getHashedKey());

        try {
            // Connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                int data;
                // Read the incoming data.
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String dbUrl, schemaVersion, checksum;
        try {
            // Get the data from tje returned JSON.
            final JSONObject jo = new JSONObject(sb.toString());
            dbUrl = jo.getString("db_url");
            schemaVersion = jo.getString("db_schema_version");
            topoId = jo.getString("topo_id");
            checksum = jo.getString("checksum");
        } catch (JSONException e) {
            // There was an error parsing the JSON, it cannot continue.
            return;
        }

        // Make sure the returned schema name is compatible with the one
        // the app uses.
        if (!BusStopDatabase.SCHEMA_NAME.equals(schemaVersion))
            return;
        // Some basic sanity checking on the parameters.
        if (topoId == null || topoId.length() == 0)
            return;
        if (dbUrl == null || dbUrl.length() == 0)
            return;
        if (checksum == null || checksum.length() == 0)
            return;

        // Make sure an update really is available.
        if (!topoId.equals(dbTopoId)) {
            // Update the database.
            updateStopsDB(context, dbUrl, checksum);
        } else if (force) {
            // Tell the user there is no update available.
            Looper.prepare();
            Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
            Looper.loop();
        }

        // Write to the SharedPreferences the last update time.
        edit.putLong("lastUpdateCheck", System.currentTimeMillis());
        edit.commit();
    }
}

From source file:edu.stanford.muse.index.NER.java

/** returns a list of <name, #occurrences> */
public static List<Pair<String, Float>> namesFromURL(String url, boolean removeCommonNames)
        throws ClassCastException, IOException, ClassNotFoundException {
    // only http conns allowed currently
    Indexer.log.info(url);/*from w  w  w . j  ava  2s .c  o m*/
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setInstanceFollowRedirects(true);
    conn.setRequestProperty("User-agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
    conn.connect();
    Indexer.log.info("url for extracting names:" + conn.getURL());
    byte[] b = Util.getBytesFromStream(conn.getInputStream());
    String text = new String(b, "UTF-8");
    text = Util.unescapeHTML(text);
    org.jsoup.nodes.Document doc = Jsoup.parse(text);
    text = doc.body().text();
    return namesFromText(text, removeCommonNames);
}

From source file:lapispaste.Main.java

private static void paster(Map<String, String> pastemap, StringBuffer pdata) {
    try {//from  w w  w.j  a  va2 s.c om
        URL url = new URL("http://paste.linux-sevenler.org/index.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // set connection 'writeable'
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // construct the data...
        String data;
        String pdataString = pdata.toString();
        data = URLEncoder.encode("language", "ISO-8859-9") + "="
                + URLEncoder.encode(pastemap.get("format"), "ISO-8859-9");
        data += "&" + URLEncoder.encode("source", "ISO-8859-9") + "="
                + URLEncoder.encode(pdataString, "ISO-8859-9");
        data += "&" + URLEncoder.encode("submit", "ISO-8859-9") + "="
                + URLEncoder.encode(" Kaydet ", "ISO-8859-9");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // get new url where the paste is
        conn.getInputStream();
        System.out.println(conn.getURL());
        conn.disconnect();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.xbmc.android.jsonrpc.io.JsonApiRequest.java

/**
 * Execute a POST request on URL using entity as request body.
 *
 * @param url/*from   w w  w .j a  va2  s  . c o  m*/
 * @param entity
 * @return The response as a string
 * @throws Exception
 * @throws IOException
 */
private static String postRequest(URL url, String user, String pass, String entity) throws Exception {
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");

    // http basic authorization
    if (user != null && !user.isEmpty() && pass != null && !pass.isEmpty()) {
        final String token = new String(Base64.encodeBase64((user + ":" + pass).getBytes(), false));
        conn.setRequestProperty("Authorization", "Basic " + token);
    }
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("User-Agent", buildUserAgent());

    conn.setConnectTimeout(REQUEST_TIMEOUT);
    conn.setReadTimeout(REQUEST_TIMEOUT);

    conn.setDoOutput(true);

    OutputStreamWriter output = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
    output.write(entity);
    output.close();

    log.info("POST request: " + conn.getURL());
    log.info("POST entity:" + entity);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = null;

    final int code = conn.getResponseCode();
    if (code == 200) {
        try {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"), 8192);
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        log.info("POST response: " + response.toString());
        return response.toString();

    } else {
        switch (code) {
        case 400:
            throw new Exception("Server says \"400 Bad HTTP request\".");
        case 401:
            throw new Exception("Server says \"401 Unauthorized\".");
        case 403:
            throw new Exception("Server says \"403 Forbidden\".");
        case 404:
            throw new Exception("Server says \"404 Not Found\".");
        default:
            if (code >= 100 && code < 200) {
                throw new Exception("Server returned informational code " + code + " instead of 200.");
            } else if (code >= 200 && code < 300) {
                throw new Exception("Server returned success code " + code + " instead of 200.");
            } else if (code >= 300 && code < 400) {
                throw new Exception("Server returned redirection code " + code + " instead of 200.");
            } else if (code >= 400 && code < 500) {
                throw new Exception("Server returned client error " + code + ".");
            } else if (code >= 500 && code < 600) {
                throw new Exception("Server returned server error " + code + ".");
            } else {
                throw new Exception("Server returned unspecified code " + code + ".");
            }
        }
    }

}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public static String readString(HttpURLConnection connection) throws Exception, UnsupportedEncodingException {
    InputStream stream = null;//ww  w .j  a  v a 2  s.  co  m
    String msg = "readString from url: ";

    try {
        int code = connection.getResponseCode();
        BufferedReader br = null;
        msg += connection.getURL().toString();

        boolean error = false;
        try {
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "readString getInputStream", "exception", e);
            error = true;
            try {
                br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            } catch (Exception e2) {
                LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "readString getErrorStream", "exception", e2);
            }
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        String str = sb.toString();
        if (error) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "readString ", "error " + str);
            return str;
        }
        return str;

    } catch (Exception ex) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "readString ", "exception", ex);
        throw (ex);
    } finally {
        //if (stream != null)
        //   try{stream.close();} catch (Exception e) {}

        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception ex) {
                LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "readString", "exception closing stream", ex);
            }
        }
    }
    //return null;
}

From source file:org.apache.ambari.server.view.HttpImpersonatorImpl.java

/**
 * @param conn HTTP connection that will be modified and returned
 * @param type HTTP Request type: GET, PUT, POST, DELETE, etc.
 * @param username Username to impersonate
 * @param doAsParamName Query param, typically "doAs"
 * @return HTTP Connection object with the doAs query param set to the provider username.
 *///  www  . j  av  a 2 s. c  om
@Override
public HttpURLConnection doAs(HttpURLConnection conn, String type, String username, String doAsParamName) {
    String url = conn.getURL().toString();
    if (url.toLowerCase().contains(doAsParamName.toLowerCase())) {
        throw new IllegalArgumentException("URL cannot contain \"" + doAsParamName + "\" parameter");
    }

    try {
        conn.setRequestMethod(type);
    } catch (IOException e) {
        return null;
    }

    conn.setRequestProperty(doAsParamName, username);
    return conn;
}

From source file:com.cloudbees.mtslaves.client.RemoteReference.java

protected void verifyResponseStatus(HttpURLConnection con) throws IOException {
    if (con.getResponseCode() / 100 != 2) {
        String msg = "Failed to call " + con.getURL() + " : " + con.getResponseCode() + ' '
                + con.getResponseMessage();
        InputStream es = con.getErrorStream();

        String ct = con.getContentType();
        if (ct != null) {
            HttpHeader contentType = HttpHeader.parse(ct);
            if (contentType.value.equals("application/json")) {
                // if the error is JSON, parse it
                if (es != null) {
                    JSONObject error = JSONObject
                            .fromObject(IOUtils.toString(es, contentType.getSubHeader("charset", "UTF-8")));
                    throw new ServerException(msg, error, con.getResponseCode(), con.getResponseMessage(),
                            con.getURL());
                }/*from w w w.ja v  a2 s  . c  om*/
            }
        }

        if (es != null)
            msg += "\n" + IOUtils.toString(es);
        throw new IOException(msg);
    }
}

From source file:com.exzogeni.dk.http.HttpTask.java

private void onPrepareConnectionInternal(HttpURLConnection cn) throws Exception {
    final URI uri = cn.getURL().toURI();
    cn.setRequestMethod(getMethodName());
    cn.setConnectTimeout(mTimeoutMs);//from w  w w.  j av a  2  s  . c o m
    cn.setReadTimeout(mTimeoutMs);
    final CookieManager cm = mHttpManager.getCookieManager();
    final Map<String, List<String>> cookies = cm.get(uri, new HashMap<String, List<String>>());
    for (final Map.Entry<String, List<String>> cookie : cookies.entrySet()) {
        for (final String value : cookie.getValue()) {
            cn.addRequestProperty(cookie.getKey(), value);
        }
    }
    for (final Map.Entry<String, List<String>> header : mHeaders.entrySet()) {
        for (final String value : header.getValue()) {
            cn.addRequestProperty(header.getKey(), value);
        }
    }
    onPrepareConnection(cn);
}

From source file:com.facebook.GraphRequestTest.java

@Test
public void testBuildsClientTokenIfNeeded() throws Exception {
    GraphRequest requestMe = new GraphRequest(null, "TourEiffel");
    HttpURLConnection connection = GraphRequest.toHttpConnection(requestMe);

    assertTrue(connection != null);/*w  w  w .j av  a2s. c om*/

    Uri uri = Uri.parse(connection.getURL().toString());
    String accessToken = uri.getQueryParameter("access_token");
    assertNotNull(accessToken);
    assertTrue(accessToken.contains(FacebookSdk.getApplicationId()));
    assertTrue(accessToken.contains(FacebookSdk.getClientToken()));
}

From source file:cn.ctyun.amazonaws.internal.EC2MetadataClient.java

/**
 * Reads a response from the Amazon EC2 Instance Metadata Service and
 * returns the content as a string./*from   w w w .  j  a  v  a  2s  . co  m*/
 *
 * @param connection
 *            The connection to the Amazon EC2 Instance Metadata Service.
 *
 * @return The content contained in the response from the Amazon EC2
 *         Instance Metadata Service.
 *
 * @throws IOException
 *             If any problems ocurred while reading the response.
 */
private String readResponse(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)
        throw new AmazonClientException("The requested metadata is not found at " + connection.getURL());

    InputStream inputStream = connection.getInputStream();

    try {
        StringBuilder buffer = new StringBuilder();
        while (true) {
            int c = inputStream.read();
            if (c == -1)
                break;
            buffer.append((char) c);
        }

        return buffer.toString();
    } finally {
        inputStream.close();
    }
}