Example usage for java.net URLEncoder encode

List of usage examples for java.net URLEncoder encode

Introduction

In this page you can find the example usage for java.net URLEncoder encode.

Prototype

@Deprecated
public static String encode(String s) 

Source Link

Document

Translates a string into x-www-form-urlencoded format.

Usage

From source file:edu.emory.bmi.medicurator.tcia.TciaQuery.java

public void param(String key, String value) {
    if (value == null)
        return;//  w w  w.j av a2s.  c  o m
    query.append(key + "=" + URLEncoder.encode(value) + "&");
}

From source file:acclaim.Acclaim.java

public String doHTTPPostRequest(String url) throws Exception {
    String rawData = "id=10";
    String type = "application/x-www-form-urlencoded";
    String encodedData = URLEncoder.encode(rawData);
    URL u = new URL("http://www.example.com/page.php");
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);/*from www.j a  v a  2 s .  c o m*/
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", type);
    conn.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
    OutputStream os = conn.getOutputStream();
    os.write(encodedData.getBytes());
    return null;
}

From source file:com.aperigeek.dropvault.dav.DropDAVClient.java

private void login() throws InvalidPasswordException, DAVException {
    String url = MessageFormat.format(LOGIN_URL, URLEncoder.encode(this.username), hash.hash(this.password));
    HttpGet get = new HttpGet(url);
    try {//from   w  ww. j  a  v  a  2 s.c o m
        HttpResponse response = client.execute(get);

        if (response.getStatusLine().getStatusCode() == 401) {
            throw new InvalidPasswordException();
        }

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new DAVException("Server error");
        }

        InputStream in = response.getEntity().getContent();
        StringWriter writer = new StringWriter();
        Reader reader = new InputStreamReader(in);
        char[] buffer = new char[128];
        int readed;
        while ((readed = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, readed);
        }
        in.close();
        baseUri = writer.toString().trim();
    } catch (IOException ex) {
        throw new DAVException("Login URL unavailable", ex);
    }
}

From source file:com.micromux.cassandra.jdbc.CollectionsTest.java

/**
 * @throws java.lang.Exception//from  ww w . ja  v a2s .co  m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {
    // configure OPTIONS
    if (!StringUtils.isEmpty(TRUST_STORE)) {
        OPTIONS = String.format("trustStore=%s&trustPass=%s", URLEncoder.encode(TRUST_STORE), TRUST_PASS);
    }

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    String URL = String.format("jdbc:cassandra://%s:%d/%s?%s&version=%s", HOST, PORT, SYSTEM, OPTIONS, CQLV3);

    con = DriverManager.getConnection(URL);

    if (LOG.isDebugEnabled())
        LOG.debug("URL         = '{}'", URL);

    Statement stmt = con.createStatement();

    // Use Keyspace
    String useKS = String.format("USE %s;", KEYSPACE);

    // Drop Keyspace
    String dropKS = String.format("DROP KEYSPACE %s;", KEYSPACE);

    try {
        stmt.execute(dropKS);
    } catch (Exception e) {
        /* Exception on DROP is OK */}

    // Create KeySpace
    String createKS = String.format(
            "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy',  'replication_factor' : 1  };",
            KEYSPACE);
    //        String createKS = String.format("CREATE KEYSPACE %s WITH strategy_class = SimpleStrategy AND strategy_options:replication_factor = 1;",KEYSPACE);
    if (LOG.isDebugEnabled())
        LOG.debug("createKS    = '{}'", createKS);

    stmt = con.createStatement();
    stmt.execute("USE " + SYSTEM);
    stmt.execute(createKS);
    stmt.execute(useKS);

    // Create the target Table (CF)
    String createTable = "CREATE TABLE testcollection (" + " k int PRIMARY KEY," + " L list<bigint>,"
            + " M map<double, boolean>, M2 map<text, timestamp>, S set<text>" + ") ;";
    if (LOG.isDebugEnabled())
        LOG.debug("createTable = '{}'", createTable);

    stmt.execute(createTable);
    stmt.close();
    con.close();

    // open it up again to see the new TABLE
    URL = String.format("jdbc:cassandra://%s:%d/%s?%s&version=%s", HOST, PORT, KEYSPACE, OPTIONS, CQLV3);
    con = DriverManager.getConnection(URL);
    if (LOG.isDebugEnabled())
        LOG.debug("URL         = '{}'", URL);

    Statement statement = con.createStatement();

    String insert = "INSERT INTO testcollection (k,L) VALUES( 1,[1, 3, 12345]);";
    statement.executeUpdate(insert);
    String update1 = "UPDATE testcollection SET S = {'red', 'white', 'blue'} WHERE k = 1;";
    String update2 = "UPDATE testcollection SET M = {2.0: true, 4.0: false, 6.0 : true} WHERE k = 1;";
    statement.executeUpdate(update1);
    statement.executeUpdate(update2);

    if (LOG.isDebugEnabled())
        LOG.debug("Unit Test: 'CollectionsTest' initialization complete.\n\n");
}

From source file:com.salsaberries.narchiver.Writer.java

/**
 * Writes all the pages to file./*from   w  ww . j  a  v a2  s. c om*/
 *
 * @param pages
 * @param location
 */
public static void storePages(LinkedList<Page> pages, String location) {

    logger.info("Dumping " + pages.size() + " pages to file at " + location + "/");

    File file = new File(location);
    // Make sure the directory exists
    if (!file.exists()) {
        try {
            file.mkdirs();
            logger.info("Directory " + file.getAbsolutePath() + " does not exist, creating.");
        } catch (SecurityException e) {
            logger.error(e.getMessage());
        }
    }
    // Write them to the file if they haven't been already written
    while (!pages.isEmpty()) {
        Page page = pages.removeFirst();

        String fileName = file.getAbsolutePath() + "/" + page.getDate() + "|"
                + URLEncoder.encode(page.getTagURL());

        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"))) {
            writer.write(page.toString());
        } catch (IOException e) {
            logger.warn(e.getMessage());
        }
        // Temporarily try to reduce memory
        page.setHtml("");
    }
}

From source file:com.captix.scan.social.facebook.Util.java

@SuppressWarnings("deprecation")
public static String encodeUrl(Bundle parameters) {
    if (parameters == null) {
        return "";
    }/*from   w w  w  . ja v  a  2s.co m*/

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : parameters.keySet()) {
        if (first)
            first = false;
        else
            sb.append("&");
        sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key)));
    }
    return sb.toString();
}

From source file:com.cloudplaylists.domain.Playlist.java

@SuppressWarnings("deprecation")
public String getUrl() {
    return url != null ? url
            : (getUserName() == null ? ("http://cloudplaylists.com/viewPlaylist?id=" + getId())
                    : ("http://cloudplaylists.com/" + URLEncoder.encode(getUserName()) + "/" + name));
}

From source file:com.browsertophone.ShareLink.java

public void send(final String link) {
    new Thread(new Runnable() {
        public void run() {
            sendToast(mContext.getString(R.string.sending_link_toast));
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("url", URLEncoder.encode(link)));
                params.add(new BasicNameValuePair("deviceType", "chrome"));
                SharedPreferences settings = Prefs.get(mContext);
                final String accountName = settings.getString("accountName", null);

                AppEngineClient client = new AppEngineClient(mContext, accountName);
                HttpResponse res = client.makeRequest(SEND_PATH, params);
                if (res.getStatusLine().getStatusCode() == 200) {
                    sendToast(mContext.getString(R.string.link_sent_toast));
                } else {
                    sendToast(mContext.getString(R.string.link_not_sent_toast));
                }/*from w w  w .  ja  va2s.  c  o m*/
            } catch (AppEngineClient.PendingAuthException e) {
                sendToast(mContext.getString(R.string.link_not_sent_auth_toast));
            } catch (Exception e) {
                sendToast(mContext.getString(R.string.link_not_sent_toast));
            }
        }
    }).start();
}

From source file:org.teleportr.plugin.BahnDePlugIn.java

public ArrayList<Ride> find(Place orig, Place dest, Date time, Teleporter tlp) {

    StringBuilder url = new StringBuilder();
    url.append("http://mobile.bahn.de/bin/mobil/query.exe/dox?");
    url.append("n=1");

    //        if (orig.city!=null)
    //           Log.d(TAG, "city: "+orig.city);
    if (orig.address != null)
        url.append("&f=2&s=")
                .append(URLEncoder.encode(orig.address + (orig.city != null ? (", " + orig.city) : "") + "!"));
    else/*  w ww.  j  a va  2  s .  c  o m*/
        url.append("&f=1&s=")
                .append(URLEncoder.encode(orig.name + (orig.city != null ? (", " + orig.city) : "") + "!"));

    if (dest.address != null)
        url.append("&o=2&z=")
                .append(URLEncoder.encode(dest.address + (dest.city != null ? (", " + dest.city) : "") + "!"));
    else
        url.append("&o=1&z=")
                .append(URLEncoder.encode(dest.name + (dest.city != null ? (", " + dest.city) : "") + "!"));

    url.append("&d="); // date
    url.append((new SimpleDateFormat("ddMMyy")).format(time));
    url.append("&t="); // time
    url.append((new SimpleDateFormat("HHmm")).format(time));
    url.append("&start=Suchen");
    //        Log.d(TAG, "url: "+url.toString());

    // fetch
    try {
        Ride r;
        MatchResult m;
        rides.clear();
        Scanner scanner = new Scanner(client.execute(new HttpGet(url.toString())).getEntity().getContent(),
                "iso-8859-1");
        Log.d(TAG, " url: " + url.toString());
        while (scanner.findWithinHorizon("<a href=\"([^\"]*)\">(\\d\\d):(\\d\\d)<br />(\\d\\d):(\\d\\d)",
                10000) != null) {
            m = scanner.match();
            Date dep = parseDate(m.group(2), m.group(3));
            if (dep.getTime() - time.getTime() > 100000) {
                r = new Ride();
                r.orig = orig;
                r.dest = dest;
                r.mode = Ride.MODE_TRANSIT;
                r.dep = dep;
                r.arr = parseDate(m.group(4), m.group(5));
                r.price = -1;
                r.fun = 3;
                r.eco = 3;
                r.fast = 1;
                r.social = 2;
                r.green = 4;
                r.uri = m.group(1).replace("&amp;", "&");

                rides.add(r);
                Log.d(TAG, " + found " + r.uri);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Mist!");
        e.printStackTrace();
    }
    return rides;
}