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:Main.java

public static SpannableString linkifyGid(String gid) {
    if (gid == null) {
        return null;
    }//from w ww . j a va 2 s . c o m
    SpannableString ret = new SpannableString(gid);
    String name = gid.substring(0, gid.lastIndexOf("@"));
    String authority = gid.substring(gid.lastIndexOf("@") + 1);
    String mainAuth = authority.contains("/") ? authority.substring(0, authority.indexOf("/")) : authority;

    if (auths.containsKey(mainAuth)) {

        String link;
        try {
            if (auths.get(mainAuth).length == 1) {
                link = auths.get(mainAuth)[0];
            } else if (auths.get(mainAuth).length == 2) {
                link = auths.get(mainAuth)[0] + URLEncoder.encode(name, "UTF-8") + auths.get(mainAuth)[1];
            } else {
                return ret;
            }
        } catch (UnsupportedEncodingException e) {
            return ret;
        }

        ret = new SpannableString(Html.fromHtml("<a href=\"" + link + "\">" + gid + "</a>"));

    } else if (mainAuth.matches(".*\\..*")) { // if it contains a dot

        // we try a link to the supposed webpage of this auth
        ret = new SpannableString(Html.fromHtml("<a href=\"http://" + mainAuth + "\">" + gid + "</a>"));

    }

    return ret;
}

From source file:Main.java

static String encode(final String value) {
    String encoded = null;/*from  www .  jav a  2 s  .c  o  m*/
    try {
        encoded = URLEncoder.encode(value, "UTF-8");
    } catch (final UnsupportedEncodingException ignore) {
    }
    if (!TextUtils.isEmpty(encoded)) {
        final StringBuilder buf = new StringBuilder(encoded.length());
        char focus;
        for (int i = 0; i < encoded.length(); i++) {
            focus = encoded.charAt(i);
            if (focus == '*') {
                buf.append("%2A");
            } else if (focus == '+') {
                buf.append("%20");
            } else if ((focus == '%') && ((i + 1) < encoded.length()) && (encoded.charAt(i + 1) == '7')
                    && (encoded.charAt(i + 2) == 'E')) {
                buf.append('~');
                i += 2;
            } else {
                buf.append(focus);
            }
        }
        return buf.toString();
    }
    return value;
}

From source file:Main.java

protected static String encodeStringArray(String[] values) {
    if (values == null || values.length == 0)
        return null;

    String valueString = null;/*from   ww w.  j  av  a 2 s.co m*/
    for (String value : values) {
        if (value != null) {
            try {
                String encodedValue = URLEncoder.encode(value, "UTF-8");
                //encodes space with "+" so change it to %20
                encodedValue = encodedValue.replaceAll("\\+", "%20");
                if (valueString == null) {
                    valueString = encodedValue;
                } else {
                    valueString += "," + encodedValue;
                }
            } catch (UnsupportedEncodingException ignored) {
            }
        }
    }
    return valueString;
}

From source file:Main.java

static String generateURLForm(HashMap<String, String> data) throws UnsupportedEncodingException {
    Set<String> keys = data.keySet();
    Iterator<String> keyIterator = keys.iterator();
    String content = "";
    for (int i = 0; keyIterator.hasNext(); i++) {
        String key = keyIterator.next();
        if (i != 0) {
            content += "&";
        }//from  w  w w  . j a v a  2s.  c  o  m
        content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8");
    }
    return content;
}

From source file:ext.sns.util.AuthUtil.java

/**
 * ?state?state????/*  w  ww .  j  av a  2  s.  co  m*/
 * 
 * @param params ?
 * @return ?state?
 */
public static String encodeState(Map<String, String> params) {
    String state = null;

    try {
        StringBuilder stateBuilder = new StringBuilder();
        for (Map.Entry<String, String> e : params.entrySet()) {
            stateBuilder.append(URLEncoder.encode(e.getKey(), "utf-8")).append('&');
            stateBuilder.append(URLEncoder.encode(e.getValue(), "utf-8")).append('&');
        }

        if (stateBuilder.length() > 0) {
            stateBuilder.deleteCharAt(stateBuilder.length() - 1);
        }

        state = URLEncoder.encode(stateBuilder.toString(), "utf-8").replace('%', '_');
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    return state;
}

From source file:de.mpg.imeji.presentation.util.SearchAndExportHelper.java

public static String getCitation(Publication publication) {
    URI uri = publication.getUri();
    URI searchAndExportUri = URI.create("http://" + uri.getHost() + "/search/SearchAndExport");
    String itemId = null;// w w w.j ava2s .c o  m
    if (uri.getQuery() != null && uri.getQuery().contains("itemId=")) {
        itemId = uri.getQuery().split("itemId=")[1];
    } else if (uri.getPath() != null && uri.getPath().contains("/item/")) {
        itemId = uri.getPath().split("/item/")[1];
    }
    if (UrlHelper.isValidURI(searchAndExportUri)) {
        try {
            HttpClient client = new HttpClient();
            String exportUri = searchAndExportUri.toString() + "?cqlQuery=" + URLEncoder.encode(
                    "escidoc.objid=" + itemId + " or escidoc.property.version.objid=" + itemId, "ISO-8859-1")
                    + "&exportFormat=" + publication.getExportFormat() + "&outputFormat=html_linked";
            GetMethod method = new GetMethod(exportUri);
            client.executeMethod(method);
            return method.getResponseBodyAsString();
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}

From source file:Main.java

@SuppressWarnings("deprecation")
static String getQueryString(List<Pair<String, String>> pairs) {
    StringBuilder queryBuilder = new StringBuilder();
    boolean first = true;
    for (Pair<String, String> pair : pairs) {
        // This will throw a NullPointerException if you call URLEncoder.encode(null).
        // Instead caught & thrown with description above.
        String value = pair.second;
        if (value == null) {
            // Can't be more specific without jeopardizing security.
            throw new NullPointerException("Malformed Request. Entry has null value for key: " + pair.first);
        }/*  ww  w  . ja va2  s . c  o m*/

        if (!first) {
            queryBuilder.append("&");
        }
        queryBuilder.append(pair.first);
        queryBuilder.append("=");
        try {
            queryBuilder.append(URLEncoder.encode(value, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // Fallback
            queryBuilder.append(URLEncoder.encode(value));
        }

        first = false;

    }

    return queryBuilder.toString();
}

From source file:com.microsoft.azure.engagement.shared.EngagementDataPushReceiver.java

public static String encodeURIComponent(String s) {
    if (s == null)
        return null;
    String result = null;//from   www.  java  2s.com
    try {

        result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!")
                .replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~");
    } catch (UnsupportedEncodingException e) {
        Log.e(EngagementShared.LOG_TAG, "Unsupported Encoding");
    }
    return result;
}

From source file:Main.java

public static String parametersToWWWFormURLEncoded(Map<String, String> parameters) throws Exception {
    StringBuilder s = new StringBuilder();
    for (Map.Entry<String, String> parameter : parameters.entrySet()) {
        if (s.length() > 0) {
            s.append("&");
        }//from   w  ww . j ava 2s.  com
        s.append(URLEncoder.encode(parameter.getKey(), "UTF-8"));
        s.append("=");
        s.append(URLEncoder.encode(parameter.getValue(), "UTF-8"));
    }
    return s.toString();
}

From source file:Main.java

public static ArrayList autocomplete(String input) {
    ArrayList resultList = null;/*from   ww  w  .  j ava  2 s .c o m*/

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        //sb.append("&components=country:gr");
        sb.append("&sensor=false");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        //Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        // Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
            System.out.println("============================================================");
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}