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:org.liberty.android.fantastischmemo.downloader.DropboxUtils.java

public static String[] retrieveToken(String username, String password) throws Exception {
    String url = TOKEN_URL + "&email=" + URLEncoder.encode(username) + "&password="
            + URLEncoder.encode(password);
    String jsonString = DownloaderUtils.downloadJSONString(url);
    JSONObject jsonObject = new JSONObject(jsonString);
    String error = null;//from   ww  w. j  a va  2 s .  c  om
    try {
        error = jsonObject.getString("error");
    } catch (JSONException e) {
        /* If error does not exist, the error will be null */
    }

    if (error != null) {
        throw new Exception(error);
    }
    String token = jsonObject.getString("token");
    String secret = jsonObject.getString("secret");
    return new String[] { token, secret };
}

From source file:fitmon.WorkoutApi.java

public StringBuilder apiGetInfo()
        throws ClientProtocolException, IOException, NoSuchAlgorithmException, InvalidKeyException {
    HttpClient client = new DefaultHttpClient();
    //HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&"
    //                    + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&"
    //                     + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=4384");
    //HttpResponse response = client.execute(request);
    //BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
    //StringBuilder sb = new StringBuilder();
    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;// w  w  w .jav  a 2s  .  c o  m

    params = "format=json&";
    params += "method=exercises.get&";
    params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key 
    params += "oauth_nonce=123&";
    params += "oauth_signature_method=HMAC-SHA1&";
    Date date = new java.util.Date();
    Timestamp ts = new Timestamp(date.getTime());
    params += "oauth_timestamp=" + ts.getTime() + "&";
    params += "oauth_version=1.0";
    //params += "search_expression=apple"; 

    String params2 = URLEncoder.encode(params);
    base += params2;
    //System.out.println(base);
    String line = "";

    String secret = "76172de2330a4e55b90cbd2eb44f8c63&";
    Mac sha256_HMAC = Mac.getInstance("HMACSHA1");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1");
    sha256_HMAC.init(secret_key);
    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes()));

    //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); 
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api?" + params
            + "&oauth_signature=" + URLEncoder.encode(hash));
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder sb = new StringBuilder();

    //$url = "http://platform.fatsecret.com/rest/server.api?"+params+"&oauth_signature="+URLEncoder.encode(hash);
    //return url;

    while ((line = rd.readLine()) != null) {
        sb.append(line);
        //System.out.println(line);
    }
    //System.out.println(sb.toString());
    return sb;
}

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

@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);
    }/*from   w  w w . j av  a2 s . com*/

    Class.forName("com.micromux.cassandra.jdbc.CassandraDriver");
    String URL = String.format("jdbc:cassandra://%s:%d/%s?version=3.0.0&%s", HOST, PORT, "system", OPTIONS);
    System.out.println("Connection URL = '" + URL + "'");

    con = DriverManager.getConnection(URL);
    Statement stmt = con.createStatement();

    // Drop Keyspace
    String dropKS1 = String.format(DROP_KS, KEYSPACE1);
    String dropKS2 = String.format(DROP_KS, KEYSPACE2);

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

    // Create KeySpace
    String createKS1 = String.format(CREATE_KS, KEYSPACE1);
    String createKS2 = String.format(CREATE_KS, KEYSPACE2);
    stmt = con.createStatement();
    stmt.execute("USE system;");
    stmt.execute(createKS1);
    stmt.execute(createKS2);

    // Use Keyspace
    String useKS1 = String.format("USE \"%s\";", KEYSPACE1);
    String useKS2 = String.format("USE \"%s\";", KEYSPACE2);
    stmt.execute(useKS1);

    // Create the target Column family
    String createCF1 = "CREATE COLUMNFAMILY test1 (keyname text PRIMARY KEY," + " t1bValue boolean,"
            + " t1iValue int" + ") WITH comment = 'first TABLE in the Keyspace'" + ";";

    String createCF2 = "CREATE COLUMNFAMILY test2 (keyname text PRIMARY KEY," + " t2bValue boolean,"
            + " t2iValue int" + ") WITH comment = 'second TABLE in the Keyspace'" + ";";

    stmt.execute(createCF1);
    stmt.execute(createCF2);
    stmt.execute(useKS2);
    stmt.execute(createCF1);
    stmt.execute(createCF2);

    stmt.close();
    con.close();

    // open it up again to see the new CF
    con = DriverManager.getConnection(
            String.format("jdbc:cassandra://%s:%d/%s?version=3.0.0&%s", HOST, PORT, KEYSPACE1, OPTIONS));

}

From source file:org.neo4j.nlp.examples.wikipedia.main.java

private static String getArticleText(String title) {
    WebResource resource = Client.create().resource(String.format(urlFormat, URLEncoder.encode(title)));

    ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);

    ObjectMapper objectMapper = new ObjectMapper();
    String result;/*from   ww  w. ja  va 2 s  . co m*/

    try {
        result = response.getEntity(String.class);
        result = Article.getExtract(result);
    } catch (Exception e) {
        throw e;
    }
    response.close();

    return result;
}

From source file:com.autburst.picture.server.PictureServer.java

public String getVideoUrl(String id, String albumName, float frameRate, String format) throws Exception {
    HttpRequest request = new HttpRequest();
    String url = BASE_URL + "/video/" + id + "/" + URLEncoder.encode(albumName) + "/" + frameRate + "/"
            + format;//from   w  ww  .j  ava 2 s  . co m
    String response = request.get(url);

    Log.d(TAG, "getVideoUrl - url: " + url);

    return response;
}

From source file:cz.autoclient.github.local.ReleaseLocal.java

public ReleaseLocal(RepositoryLocal parent, JSONObject elm) {
    String tag = "";
    URL url = null;//  ww  w .  j  a  v  a 2s . com
    String description = null;
    boolean isLatest = false;
    boolean isPre = false;
    try {
        tag = elm.getString("tag_name");
        description = elm.getString("body");
        //https://github.com/twbs/bootstrap/releases/tag/v1.4.0
        url = new URL(parent.getURL(), "releases/" + URLEncoder.encode(tag) + "/");
        System.out.println("Release " + tag + " at " + url.toString());
        //loadDownloads(elm);
        // The release label
        isPre = elm.getBoolean("prerelease");
        isLatest = false;
    } catch (JSONException ex) {
        Logger.getLogger(ReleaseLocal.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        throw new IllegalArgumentException(
                "Invalid path  created invalid URL: " + parent.getURL() + "/releases/tag/" + tag);
    }
    this.tag = tag;
    this.description = description;
    //https://github.com/twbs/bootstrap/releases/tag/v1.4.0
    this.parent = parent;
    this.url = url;

    this.isPre = isPre;
    this.isLatest = isLatest;
    try {
        loadDownloads(elm.getJSONArray("assets"));
    } catch (JSONException ex) {
        System.out.println("Failed to parse released files.");
        ex.printStackTrace();
    }
}

From source file:com.bakhtiyor.android.calculator.NigmaService.java

public List<String> getChemicalReactions(String reaction) {
    String url = String.format(URL_PATTERN, URLEncoder.encode(reaction));
    byte[] response = fetch(url);
    List<String> results = new ArrayList<String>();
    if (response != null) {
        String responseString = new String(response);
        Matcher matcher = REACT_PATTERN.matcher(responseString);
        while (matcher.find()) {
            String cleared = matcher.group(1).replaceAll("(?i)\\<([\\s/]?)(a|s|u).*?\\>", "")
                    .replaceAll("\\(((\\<.*?\\>)*?)(\\W+?)((\\<\\.*?\\>)*?)\\)", "")
                    .replaceAll("(\\p{InCyrillic}*?)", "");
            results.add(cleared);//  w ww  .  j a  v a  2 s  .com
        }
    }
    return !results.isEmpty() ? results : Collections.<String>emptyList();
}

From source file:URLUtilities.java

/**
 * Calls <code>java.net.URLEncoder.encode(String, String)</code> via
 * reflection, if we are running on JRE 1.4 or later, otherwise reverts to
 * the deprecated <code>URLEncoder.encode(String)</code> method.
 *
 * @param s  the string to encode./* ww w  . j  a  va 2 s.  c o m*/
 * @param encoding  the encoding.
 *
 * @return The encoded string.
 *
 * @since 1.0.6
 */
public static String encode(String s, String encoding) {
    Class c = URLEncoder.class;
    String result = null;
    try {
        Method m = c.getDeclaredMethod("encode", STRING_ARGS_2);
        try {
            result = (String) m.invoke(null, new Object[] { s, encoding });
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    } catch (NoSuchMethodException e) {
        // we're running on JRE 1.3.1 so this is the best we have...
        result = URLEncoder.encode(s);
    }
    return result;
}

From source file:fitmon.DietAPI.java

public ArrayList<Food> getFood(String foodID) throws ClientProtocolException, IOException,
        NoSuchAlgorithmException, InvalidKeyException, SAXException, ParserConfigurationException {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&"
            + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&"
            + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=33691");
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;//from  w ww  . j  av  a  2s  . co m

    params = "food_id=" + foodID + "&";
    params += "method=food.get&";
    params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key 
    params += "oauth_nonce=123&";
    params += "oauth_signature_method=HMAC-SHA1&";
    Date date = new java.util.Date();
    Timestamp ts = new Timestamp(date.getTime());
    params += "oauth_timestamp=" + ts.getTime() + "&";
    params += "oauth_version=1.0";
    //params += "search_expression=apple"; 

    String params2 = URLEncoder.encode(params);
    base += params2;
    System.out.println(base);
    String line = "";

    String secret = "76172de2330a4e55b90cbd2eb44f8c63&";
    Mac sha256_HMAC = Mac.getInstance("HMACSHA1");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1");
    sha256_HMAC.init(secret_key);
    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes()));

    //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); 

    String url = "http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature="
            + URLEncoder.encode(hash);
    System.out.println(url);
    xmlParser xParser = new xmlParser();
    ArrayList<Food> foodList = xParser.Parser(url);
    return foodList;
    //while ((line = rd.readLine()) != null) {
    //  System.out.println(line);
    //}
}

From source file:in.flipbrain.Utils.java

public static String httpGet(String uri, HashMap<String, String> params) {
    StringBuilder query = new StringBuilder();
    for (Map.Entry<String, String> entrySet : params.entrySet()) {
        String key = entrySet.getKey();
        String value = entrySet.getValue();
        query.append(URLEncoder.encode(key)).append("=");
        query.append(URLEncoder.encode(value)).append("&");
    }//from  w  w w  . j av a2  s. c om
    if (query.length() > 0) {
        query.insert(0, "?").insert(0, uri);
    }
    String res = null;
    try {
        String fullUrl = query.toString();
        logger.debug("Request URL: " + fullUrl);
        res = Request.Get(fullUrl).execute().returnContent().asString();
        logger.debug("Response: " + res);
    } catch (IOException e) {
        logger.fatal("Failed to process request. ", e);
    }
    return res;
}