Example usage for android.net Uri encode

List of usage examples for android.net Uri encode

Introduction

In this page you can find the example usage for android.net Uri encode.

Prototype

public static String encode(String s, String allow) 

Source Link

Document

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme.

Usage

From source file:ir.rasen.charsoo.controller.image_loader.core.download.BaseImageDownloader.java

/**
 * Create {@linkplain HttpURLConnection HTTP connection} for incoming URL
 *
 * @param url   URL to connect to//from w  w w.ja v  a 2  s.co  m
 * @param extra Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *              DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@linkplain HttpURLConnection Connection} for incoming URL. Connection isn't established so it still configurable.
 * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected HttpURLConnection createConnection(String url, Object extra) throws IOException {
    String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
    HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection();
    conn.setConnectTimeout(connectTimeout);
    conn.setReadTimeout(readTimeout);
    return conn;
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

/** Called when the activity is first created. */
@Override// w w  w  . ja va  2  s .c o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    fixScreenOrientation();

    DoCommand dc = new DoCommand(getApplication());

    Log.i("SUTAgentAndroid", dc.prgVersion);
    dc.FixDataLocalPermissions();

    // Get configuration settings from "ini" file
    File dir = getFilesDir();
    File iniFile = new File(dir, "SUTAgent.ini");
    String sIniFile = iniFile.getAbsolutePath();

    String lc = dc.GetIniData("General", "LogCommands", sIniFile);
    if (lc != "" && Integer.parseInt(lc) == 1) {
        SUTAgentAndroid.LogCommands = true;
    }
    SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile);
    SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile);
    SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile);
    SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile);
    SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile);
    SUTAgentAndroid.Abi = android.os.Build.CPU_ABI;
    log(dc, "onCreate");

    dc.SetTestRoot(SUTAgentAndroid.sTestRoot);

    Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot);

    tv = (TextView) this.findViewById(R.id.Textview01);

    if (getLocalIpAddress() == null)
        setUpNetwork(sIniFile);

    String macAddress = "Unknown";
    if (android.os.Build.VERSION.SDK_INT > 8) {
        try {
            NetworkInterface iface = NetworkInterface
                    .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]);
            if (iface != null) {
                byte[] mac = iface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    Formatter f = new Formatter(sb);
                    for (int i = 0; i < mac.length; i++) {
                        f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : "");
                    }
                    macAddress = sUniqueID = sb.toString();
                }
            }
        } catch (UnknownHostException ex) {
        } catch (SocketException ex) {
        }
    } else {
        // Fall back to getting info from wifiman on older versions of Android,
        // which don't support the NetworkInterface interface
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiMan != null) {
            WifiInfo wifi = wifiMan.getConnectionInfo();
            if (wifi != null)
                macAddress = wifi.getMacAddress();
            if (macAddress != null)
                sUniqueID = macAddress;
        }
    }

    if (sUniqueID == null) {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if ((ba != null) && (ba.isEnabled() != true)) {
            ba.enable();
            while (ba.getState() != BluetoothAdapter.STATE_ON) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sUniqueID = ba.getAddress();

            ba.disable();
            while (ba.getState() != BluetoothAdapter.STATE_OFF) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (ba != null) {
                sUniqueID = ba.getAddress();
                sUniqueID.toLowerCase();
            }
        }
    }

    if (sUniqueID == null) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mTelephonyMgr != null) {
            sUniqueID = mTelephonyMgr.getDeviceId();
            if (sUniqueID == null) {
                sUniqueID = "0011223344556677";
            }
        }
    }

    String hwid = getHWID(this);

    sLocalIPAddr = getLocalIpAddress();
    Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...",
            Toast.LENGTH_LONG).show();

    String sConfig = dc.prgVersion + lineSep;
    sConfig += "Test Root: " + sTestRoot + lineSep;
    sConfig += "Unique ID: " + sUniqueID + lineSep;
    sConfig += "HWID: " + hwid + lineSep;
    sConfig += "ABI: " + Abi + lineSep;
    sConfig += "OS Info" + lineSep;
    sConfig += "\t" + dc.GetOSInfo() + lineSep;
    sConfig += "Screen Info" + lineSep;
    int[] xy = dc.GetScreenXY();
    sConfig += "\t Width: " + xy[0] + lineSep;
    sConfig += "\t Height: " + xy[1] + lineSep;
    sConfig += "Memory Info" + lineSep;
    sConfig += "\t" + dc.GetMemoryInfo() + lineSep;
    sConfig += "Network Info" + lineSep;
    sConfig += "\tMac Address: " + macAddress + lineSep;
    sConfig += "\tIP Address: " + sLocalIPAddr + lineSep;

    displayStatus(sConfig);

    sRegString = "NAME=" + sUniqueID;
    sRegString += "&IPADDR=" + sLocalIPAddr;
    sRegString += "&CMDPORT=" + 20701;
    sRegString += "&DATAPORT=" + 20700;
    sRegString += "&OS=Android-" + dc.GetOSInfo();
    sRegString += "&SCRNWIDTH=" + xy[0];
    sRegString += "&SCRNHEIGHT=" + xy[1];
    sRegString += "&BPP=8";
    sRegString += "&MEMORY=" + dc.GetMemoryConfig();
    sRegString += "&HARDWARE=" + HardwareID;
    sRegString += "&POOL=" + Pool;
    sRegString += "&ABI=" + Abi;

    String sTemp = Uri.encode(sRegString, "=&");
    sRegString = "register " + sTemp;

    pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot());

    if (!bNetworkingStarted) {
        Thread thread = new Thread(null, doStartService, "StartServiceBkgnd");
        thread.start();
        bNetworkingStarted = true;

        Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd");
        thread2.start();
    }

    monitorBatteryState();

    // If we are returning from an update let'em know we're back
    Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd");
    thread3.start();

    final Button goButton = (Button) findViewById(R.id.Button01);
    goButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
}

From source file:website.openeng.async.Connection.java

/**
 * Downloads any missing media files according to the mediaURL deckvar.
 *
 * @param data/*  w  ww  .  j  av  a2 s  . co m*/
 * @return The return type contains data.resultType and an array of Integer in data.data. data.data[0] is the number
 *         of total missing media, data.data[1] is the number of downloaded ones.
 */
private Payload doInBackgroundDownloadMissingMedia(Payload data) {
    Timber.i("DownloadMissingMedia");
    HashMap<String, String> missingPaths = new HashMap<String, String>();
    HashMap<String, String> missingSums = new HashMap<String, String>();

    data.result = (Decks) data.data[0]; // pass it to the return object so we close the deck in the deck picker
    String syncName = "";// deck.getDeckName();

    data.success = false;
    data.data = new Object[] { 0, 0, 0 };
    // if (!deck.hasKey("mediaURL")) {
    // data.success = true;
    // return data;
    // }
    String urlbase = "";// deck.getVar("mediaURL");
    if (urlbase.equals("")) {
        data.success = true;
        return data;
    }

    String mdir = "";// deck.mediaDir(true);
    int totalMissing = 0;
    int missing = 0;
    int grabbed = 0;

    Cursor cursor = null;
    try {
        cursor = null;// deck.getDB().getDatabase().rawQuery("SELECT filename, originalPath FROM media", null);
        String path = null;
        String f = null;
        while (cursor.moveToNext()) {
            f = cursor.getString(0);
            path = mdir + "/" + f;
            File file = new File(path);
            if (!file.exists()) {
                missingPaths.put(f, path);
                missingSums.put(f, cursor.getString(1));
                Timber.d("Missing file: %s", f);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    totalMissing = missingPaths.size();
    data.data[0] = totalMissing;
    if (totalMissing == 0) {
        data.success = true;
        return data;
    }
    publishProgress(Boolean.FALSE, totalMissing, 0, syncName);

    URL url = null;
    HttpURLConnection connection = null;
    String path = null;
    String sum = null;
    int readbytes = 0;
    byte[] buf = new byte[4096];
    for (String file : missingPaths.keySet()) {

        try {
            android.net.Uri uri = android.net.Uri.parse(Uri.encode(urlbase, ":/@%") + Uri.encode(file));
            url = new URI(uri.toString()).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                path = missingPaths.get(file);
                InputStream is = connection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is, 4096);
                FileOutputStream fos = new FileOutputStream(path);
                while ((readbytes = bis.read(buf, 0, 4096)) != -1) {
                    fos.write(buf, 0, readbytes);
                    Timber.d("Downloaded %d file: %s", readbytes, path);
                }
                fos.close();

                // Verify with checksum
                sum = missingSums.get(file);
                if (true) {// sum.equals("") || sum.equals(Utils.fileChecksum(path))) {
                    grabbed++;
                } else {
                    // Download corrupted, delete file
                    Timber.i("Downloaded media file %s failed checksum.", path);
                    File f = new File(path);
                    f.delete();
                    missing++;
                }
            } else {
                Timber.e("Connection error (" + connection.getResponseCode() + ") while retrieving media file "
                        + urlbase + file);
                Timber.e("Connection message: " + connection.getResponseMessage());
                if (missingSums.get(file).equals("")) {
                    // Ignore and keep going
                    missing++;
                } else {
                    data.success = false;
                    data.data = new Object[] { file };
                    return data;
                }
            }
            connection.disconnect();
        } catch (URISyntaxException e) {
            Timber.e(e, "doInBackgroundDownloadMissingMedia URISyntaxException");
        } catch (MalformedURLException e) {
            Timber.e(e, "MalformedURLException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } catch (IOException e) {
            Timber.e(e, "IOException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        publishProgress(Boolean.TRUE, totalMissing, grabbed + missing, syncName);
    }

    data.data[1] = grabbed;
    data.data[2] = missing;
    data.success = true;
    return data;
}

From source file:free.yhc.feeder.model.Utils.java

public static String buildYoutubeFeedUrl_uploader(String uploader) {
    return "http://gdata.youtube.com/feeds/api/users/" + Uri.encode(uploader, null) + "/uploads?format=5";
}

From source file:free.yhc.feeder.model.Utils.java

public static String buildYoutubeFeedUrl_search(String search) {
    search = search.replaceAll("\\s+", "+");
    return "http://gdata.youtube.com/feeds/api/videos?q=" + Uri.encode(search, "+")
            + "&start-index=1&max-results=50&client=ytapi-youtube-search&orderby=published&format=5&v=2";
}

From source file:com.hichinaschool.flashcards.async.Connection.java

/**
 * Downloads any missing media files according to the mediaURL deckvar.
 * /*w  w  w.j av a2 s. co m*/
 * @param data
 * @return The return type contains data.resultType and an array of Integer in data.data. data.data[0] is the number
 *         of total missing media, data.data[1] is the number of downloaded ones.
 */
private Payload doInBackgroundDownloadMissingMedia(Payload data) {
    // Log.i(AnkiDroidApp.TAG, "DownloadMissingMedia");
    HashMap<String, String> missingPaths = new HashMap<String, String>();
    HashMap<String, String> missingSums = new HashMap<String, String>();

    Decks deck = (Decks) data.data[0];
    data.result = deck; // pass it to the return object so we close the deck in the deck picker
    String syncName = "";// deck.getDeckName();

    data.success = false;
    data.data = new Object[] { 0, 0, 0 };
    // if (!deck.hasKey("mediaURL")) {
    // data.success = true;
    // return data;
    // }
    String urlbase = "";// deck.getVar("mediaURL");
    if (urlbase.equals("")) {
        data.success = true;
        return data;
    }

    String mdir = "";// deck.mediaDir(true);
    int totalMissing = 0;
    int missing = 0;
    int grabbed = 0;

    Cursor cursor = null;
    try {
        cursor = null;// deck.getDB().getDatabase().rawQuery("SELECT filename, originalPath FROM media", null);
        String path = null;
        String f = null;
        while (cursor.moveToNext()) {
            f = cursor.getString(0);
            path = mdir + "/" + f;
            File file = new File(path);
            if (!file.exists()) {
                missingPaths.put(f, path);
                missingSums.put(f, cursor.getString(1));
                // Log.i(AnkiDroidApp.TAG, "Missing file: " + f);
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    totalMissing = missingPaths.size();
    data.data[0] = new Integer(totalMissing);
    if (totalMissing == 0) {
        data.success = true;
        return data;
    }
    publishProgress(Boolean.FALSE, new Integer(totalMissing), new Integer(0), syncName);

    URL url = null;
    HttpURLConnection connection = null;
    String path = null;
    String sum = null;
    int readbytes = 0;
    byte[] buf = new byte[4096];
    for (String file : missingPaths.keySet()) {

        try {
            android.net.Uri uri = android.net.Uri.parse(Uri.encode(urlbase, ":/@%") + Uri.encode(file));
            url = new URI(uri.toString()).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                path = missingPaths.get(file);
                InputStream is = connection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is, 4096);
                FileOutputStream fos = new FileOutputStream(path);
                while ((readbytes = bis.read(buf, 0, 4096)) != -1) {
                    fos.write(buf, 0, readbytes);
                    // Log.i(AnkiDroidApp.TAG, "Downloaded " + readbytes + " file: " + path);
                }
                fos.close();

                // Verify with checksum
                sum = missingSums.get(file);
                if (true) {// sum.equals("") || sum.equals(Utils.fileChecksum(path))) {
                    grabbed++;
                } else {
                    // Download corrupted, delete file
                    // Log.i(AnkiDroidApp.TAG, "Downloaded media file " + path + " failed checksum.");
                    File f = new File(path);
                    f.delete();
                    missing++;
                }
            } else {
                Log.e(AnkiDroidApp.TAG, "Connection error (" + connection.getResponseCode()
                        + ") while retrieving media file " + urlbase + file);
                Log.e(AnkiDroidApp.TAG, "Connection message: " + connection.getResponseMessage());
                if (missingSums.get(file).equals("")) {
                    // Ignore and keep going
                    missing++;
                } else {
                    data.success = false;
                    data.data = new Object[] { file };
                    return data;
                }
            }
            connection.disconnect();
        } catch (URISyntaxException e) {
            Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
        } catch (MalformedURLException e) {
            Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
            Log.e(AnkiDroidApp.TAG, "MalformedURLException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } catch (IOException e) {
            Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e));
            Log.e(AnkiDroidApp.TAG, "IOException while download media file " + path);
            if (missingSums.get(file).equals("")) {
                // Ignore and keep going
                missing++;
            } else {
                data.success = false;
                data.data = new Object[] { file };
                return data;
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        publishProgress(Boolean.TRUE, new Integer(totalMissing), new Integer(grabbed + missing), syncName);
    }

    data.data[1] = new Integer(grabbed);
    data.data[2] = new Integer(missing);
    data.success = true;
    return data;
}