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

public static String encode(String s, Charset charset) 

Source Link

Document

Translates a string into application/x-www-form-urlencoded format using a specific java.nio.charset.Charset Charset .

Usage

From source file:com.dianping.lion.util.UrlUtils.java

public static String resolveUrl(Map<String, ?> parameters, String... includes) {
    StringBuilder url = new StringBuilder();
    int index = 0;
    try {//  w w w.jav  a2s . co m
        if (parameters != null) {
            for (Entry<String, ?> entry : parameters.entrySet()) {
                Collection<Object> paramValues = new ArrayList<Object>();
                Object paramValue = entry.getValue();
                if (ArrayUtils.isEmpty(includes) || ArrayUtils.contains(includes, entry.getKey())) {
                    Class<? extends Object> paramClass = paramValue.getClass();
                    if (Collection.class.isInstance(paramValue)) {
                        paramValues.addAll((Collection<?>) paramValue);
                    } else if (paramClass.isArray()) {
                        Object[] valueArray = (Object[]) paramValue;
                        for (Object value : valueArray) {
                            paramValues.add(value);
                        }
                    } else {
                        paramValues.add(paramValue);
                    }
                    for (Object value : paramValues) {
                        url.append(index++ == 0 ? "" : "&").append(entry.getKey()).append("=")
                                .append(URLEncoder.encode(value.toString(), "utf-8"));
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return url.toString();
}

From source file:net.myrrix.common.io.IOUtils.java

/**
 * @param raw string to URL-encode//from  w  ww. jav a  2s. com
 * @return the URL encoding of the argument, using the UTF-8 encoding if necessary to interpret
 *  characters as bytes
 */
public static String urlEncode(String raw) {
    try {
        return URLEncoder.encode(raw, Charsets.UTF_8.name());
    } catch (UnsupportedEncodingException uee) {
        // Can't happen for UTF-8
        throw new AssertionError(uee);
    }
}

From source file:com.shahnami.fetch.Controller.FetchSeries.java

public List<Show> getShows(String query) {
    try {//from w w w. j a va2  s.  c  o m
        JSONArray json = JsonReader.readJsonArrayFromUrl("http://eztvapi.re/shows");
        for (int i = 1; i < json.length() + 1; i++) {
            JSONArray shows = JsonReader.readJsonArrayFromUrl(
                    "http://eztvapi.re/shows/" + i + "?keywords=" + URLEncoder.encode(query, "UTF-8"));
            if (shows.length() > 0) {
                for (int j = 0; j < shows.length(); j++) {
                    String id = shows.getJSONObject(j).getString("_id");
                    String title = shows.getJSONObject(j).getString("title");
                    String year = shows.getJSONObject(j).getString("year");
                    if (year.equalsIgnoreCase("null")) {
                        year = "-----";
                    }
                    int rating = shows.getJSONObject(j).getJSONObject("rating").getInt("percentage");
                    String poster = shows.getJSONObject(j).getJSONObject("images").getString("poster");
                    int num_seasons = shows.getJSONObject(j).getInt("num_seasons");
                    long last_updated = shows.getJSONObject(j).getLong("last_updated");
                    Show s = new Show();
                    s.setId(id);
                    s.setTitle(title);
                    s.setYear(year);
                    s.setPercentage(rating);
                    s.setPoster(poster);
                    s.setNum_seasons(num_seasons);
                    s.setLast_updated(last_updated);
                    _shows.add(s);
                }
            }
        }

    } catch (IOException | JSONException ex) {
        Logger.getLogger(FetchSeries.class.getName()).log(Level.SEVERE, null, ex);
    }
    return _shows;
}

From source file:fr.free.nrw.commons.Utils.java

/**
 * URL Encode an URL in UTF-8 format/*from ww  w.  j a va 2s. c o m*/
 * @param url Unformatted URL
 * @return Encoded URL
 */
public static String urlEncode(String url) {
    try {
        return URLEncoder.encode(url, "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * Creates a URL for a request to the Dropbox API.
 *
 * @param host the Dropbox host (i.e., api server, content server, or web
 *         server)./*from  ww  w .j a  va  2 s  .c o  m*/
 * @param apiVersion the API version to use. You should almost always use
 *         {@code DropboxAPI.VERSION} for this.
 * @param target the target path, staring with a '/'.
 * @param params any URL params in an array, with the even numbered
 *         elements the parameter names and odd numbered elements the
 *         values, e.g. <code>new String[] {"path", "/Public", "locale",
 *         "en"}</code>.
 *
 * @return a full URL for making a request.
 */
public static String buildURL(String host, int apiVersion, String target, String[] params) {
    if (!target.startsWith("/")) {
        target = "/" + target;
    }

    try {
        // We have to encode the whole line, then remove + and / encoding
        // to get a good OAuth URL.
        target = URLEncoder.encode("/" + apiVersion + target, "UTF-8");
        target = target.replace("%2F", "/");

        if (params != null && params.length > 0) {
            target += "?" + urlencode(params);
        }

        // These substitutions must be made to keep OAuth happy.
        target = target.replace("+", "%20").replace("*", "%2A");
    } catch (UnsupportedEncodingException uce) {
        return null;
    }

    return "https://" + host + ":443" + target;
}

From source file:com.memetix.gun4j.expand.UrlExpander.java

public static Map<String, String> expand(final Set<String> shortUrls) throws Exception {
    final StringBuilder sb = new StringBuilder();

    int i = 0;// ww w . jav  a2s.  c  o m
    for (String shortUrl : shortUrls) {
        if (i > 0) {
            sb.append(AMPERSAND);
        }
        sb.append(PARAM_NAME);
        sb.append(EQUALS);
        sb.append(URLEncoder.encode(shortUrl, ENCODING));
        i++;
    }

    Map<String, String> results = parseResponse(post(SERVICE_URL, sb.toString()));
    return results;
}

From source file:max.hubbard.bettershops.Utils.ItemUtils.java

private static String mapToString(Map<String, Object> map) {
    StringBuilder stringBuilder = new StringBuilder();
    for (String key : map.keySet()) {
        if (stringBuilder.length() > 0) {
            stringBuilder.append("&");
        }/* w ww.j  a  v  a2s  .co m*/
        String value = map.get(key).toString();
        try {
            stringBuilder.append((key != null ? URLEncoder.encode(key, "UTF-8") : ""));
            stringBuilder.append("=");
            stringBuilder.append(value != null ? URLEncoder.encode(value, "UTF-8") : "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("This method requires UTF-8 encoding support", e);
        }
    }
    return stringBuilder.toString();
}

From source file:com.grouptuity.venmo.VenmoSDK.java

public static Intent openVenmoPayment(String myAppId, String myAppName, String recipients, String amount,
        String note, String txn) {
    String venmo_uri = "venmosdk://paycharge?txn=" + txn;

    if (!recipients.equals("")) {
        try {/*from w  w  w  .  j  av  a  2 s  . c o  m*/
            venmo_uri += "&recipients=" + URLEncoder.encode(recipients, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e("venmodemo", "cannot encode recipients");
        }
    }
    if (!amount.equals("")) {
        try {
            venmo_uri += "&amount=" + URLEncoder.encode(amount, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e("venmodemo", "cannot encode amount");
        }
    }
    if (!note.equals("")) {
        try {
            venmo_uri += "&note=" + URLEncoder.encode(note, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            Log.e("venmodemo", "cannot encode note");
        }
    }

    try {
        venmo_uri += "&app_id=" + URLEncoder.encode(myAppId, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e("venmodemo", "cannot encode app ID");
    }
    try {
        venmo_uri += "&app_name=" + URLEncoder.encode(myAppName, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e("venmodemo", "cannot encode app Name");
    }
    try {
        venmo_uri += "&app_local_id=" + URLEncoder.encode("abcd", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e("venmodemo", "cannot encode app local id");
    }

    venmo_uri += "&using_new_sdk=true";
    venmo_uri = venmo_uri.replaceAll("\\+", "%20"); // use %20 encoding instead of +

    return new Intent(Intent.ACTION_VIEW, Uri.parse(venmo_uri));
}

From source file:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {/*w  ww  .  j  a va 2  s  . com*/
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:com.miyue.util.EncoderUtil.java

/**
 * URL ?, EncodeGBK. //from ww  w  .  j  ava 2s . com
 */
public static String URLEncodeGBK(String input) {
    try {
        return URLEncoder.encode(input, GBK_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unsupported Encoding Exception", e);
    }
}