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 HttpEntity getEntity(String uri, ArrayList<BasicNameValuePair> params, int method)
        throws ClientProtocolException, IOException {
    mClient = new DefaultHttpClient();
    HttpUriRequest request = null;/*from w  w  w.jav a2 s .  c  o m*/
    switch (method) {
    case METHOD_GET:
        StringBuilder sb = new StringBuilder(uri);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            for (BasicNameValuePair param : params) {
                sb.append(param.getName()).append("=").append(URLEncoder.encode(param.getValue(), "UTF_8"))
                        .append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        request = new HttpGet(sb.toString());
        break;
    case METHOD_POST:
        HttpPost post = new HttpPost(uri);
        if (params != null && !params.isEmpty()) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF_8");
            post.setEntity(entity);
        }
        request = post;
        break;
    }
    mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
    HttpResponse response = mClient.execute(request);
    System.err.println(response.getStatusLine().toString());
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response.getEntity();
    }
    return null;
}

From source file:com.taobao.ad.easyschedule.commons.utils.WangWangUtil.java

/**
 * ??//  w ww  .  jav a  2  s  .com
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendWangWang(String list, String subject, String content) {

    if ("false".equals(Constants.SENDWANGWANG) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)
            || StringUtils.isEmpty(content)) {
        return;
    }
    try {
        String command = Constants.WANGWANG_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 900) {
            strContent = StringUtil.bSubstring(content, 899);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK")).replaceAll("#content#",
                        URLEncoder.encode(StringUtils.isEmpty(strContent) ? "null" : strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("WangWangUtil.sendWangWang statusCode:" + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("WangWangUtil.sendWangWang", e);
    }
}

From source file:Main.java

/**
 * Given an un-encoded URI query string, this will return a normalized, properly encoded URI query string.
 * <b>Important:</b> This method uses java's URLEncoder, which returns things that are 
 * application/x-www-form-urlencoded, instead of things that are properly octet-esacped as the URI spec
 * requires.  As a result, some substitutions are made to properly translate space characters to meet the
 * URI spec./*from   w  ww. j a  va 2 s .  co  m*/
 * @param queryString
 * @return
 */
private static String normalizeQueryString(String queryString) throws UnsupportedEncodingException {
    if ("".equals(queryString) || queryString == null)
        return queryString;

    String[] pieces = queryString.split("&");
    HashMap<String, String> kvp = new HashMap<String, String>();
    StringBuffer builder = new StringBuffer("");

    for (int x = 0; x < pieces.length; x++) {
        String[] bs = pieces[x].split("=", 2);
        bs[0] = URLEncoder.encode(bs[0], "UTF-8");
        if (bs.length == 1)
            kvp.put(bs[0], null);
        else {
            kvp.put(bs[0], URLEncoder.encode(bs[1], "UTF-8").replaceAll("\\+", "%20"));
        }
    }

    // Sort the keys alphabetically, ignoring case.
    ArrayList<String> keys = new ArrayList<String>(kvp.keySet());
    Collections.sort(keys, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2);
        }
    });

    // With the alphabetic list of parameter names, re-build the query string.
    for (int x = 0; x < keys.size(); x++) {
        // Some parameters have no value, and are simply present.  If so, we put null in kvp,
        // and we just put the parameter name, no "=value".
        if (kvp.get(keys.get(x)) == null)
            builder.append(keys.get(x));
        else
            builder.append(keys.get(x) + "=" + kvp.get(keys.get(x)));

        if (x < (keys.size() - 1))
            builder.append("&");
    }

    return builder.toString();
}

From source file:cc.vidr.datum.builtin.FreebaseSearch.java

/**
 * Return the atom that is the best match for the given query.
 * /*from   w w  w.java 2  s .c  o m*/
 * @param query  the query
 * @return       the atom
 */
private static Atom search(String query) throws Exception {
    List<JSONObject> result = FreebaseUtils.getResultList(path + URLEncoder.encode(query, "UTF-8"));
    JSONObject result0 = result.get(0);
    String id = (String) result0.get("id");
    return FreebaseUtils.atomFromID(id);
}

From source file:com.taobao.ad.easyschedule.commons.utils.SmsUtil.java

/**
 * ??// w  ww .  j a  v a  2  s.co  m
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendSMS(String list, String subject, String content) {
    if ("false".equals(Constants.SENDSMS) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.SMS_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = subject;
        if (subject.getBytes().length > 150) {
            // ????content?subjectcontent??
            strContent = StringUtil.bSubstring(subject + ":" + content, 149);
        }
        command = command.replaceAll("#list#", URLEncoder.encode(list, "GBK"))
                .replaceAll("#subject#", URLEncoder.encode(strSubject, "GBK"))
                .replaceAll("#content#", URLEncoder.encode(strContent, "GBK"));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.NOTIFY_API_CONN_TIMEOUT);
        GetMethod getMethod = new GetMethod(command);
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        for (int i = 1; i <= 3; i++) {
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("SmsUtil.sendWangWang statusCode:" + statusCode);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                String ret = getMethod.getResponseBodyAsString();
                if (!"OK".equals(ret)) {
                    logger.error("Send message failed[" + i + "];list:" + list + ";subject:" + subject
                            + ";content:" + content);
                    sendSMSByShell(list, "es:" + subject);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                logger.error("Send message failed[" + i + "]:" + e.getMessage());
                Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("SmsUtil.sendSMS", e);
    }
}

From source file:Main.java

/**
 * Creates an XIInclude element with a link to a file
 *
 * @param doc  The DOM Document to create the xi:include for.
 * @param file The file name/path to link to.
 * @return An xi:include element that can be used to include content from another file.
 *//*from   w ww .j  a  v  a  2 s. c om*/
public static Element createXIInclude(final Document doc, final String file) {
    try {
        // Encode the file reference
        final StringBuilder fixedFileRef = new StringBuilder();
        final String[] split = file.split("/");
        for (int i = 0; i < split.length; i++) {
            if (i != 0) {
                fixedFileRef.append("/");
            }

            final String uriPart = split[i];
            if (uriPart.isEmpty() || uriPart.equals("..") || uriPart.equals(".")) {
                fixedFileRef.append(uriPart);
            } else {
                fixedFileRef.append(URLEncoder.encode(uriPart, "UTF-8"));
            }
        }

        // If the file ref ended with "/" then it wouldn't have been added as their was no content after it
        if (file.endsWith("/")) {
            fixedFileRef.append("/");
        }

        final Element xiInclude = doc.createElementNS("http://www.w3.org/2001/XInclude", "xi:include");
        xiInclude.setAttribute("href", fixedFileRef.toString());
        xiInclude.setAttribute("xmlns:xi", "http://www.w3.org/2001/XInclude");

        return xiInclude;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.newtouch.util.utils.encode.EncodeUtils.java

/**
 * URL ?, EncodeUTF-8. /*  w  ww  .j  a  v  a 2s  .  c o m*/
 */
public static String urlEncode(String input) {
    try {
        return URLEncoder.encode(input, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unsupported Encoding Exception", e);
    }
}

From source file:io.pivotal.cla.mvc.util.UrlBuilder.java

@Builder(builderMethodName = "signUrl")
@SneakyThrows/*from www .  ja v  a2s.c  o m*/
private static String createSignUrl(HttpServletRequest request, String claName, String repositoryId,
        int pullRequestId) {
    String urlEncodedClaName = URLEncoder.encode(claName, "UTF-8");
    UrlBuilder url = UrlBuilder //
            .fromRequest(request) //
            .path("/sign/" + urlEncodedClaName) //
            .param("repositoryId", repositoryId) //
            .param("pullRequestId", String.valueOf(pullRequestId));
    return url.build();
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doGET(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;//  w w w  .ja v a 2s .  c  o m
    String content = "";
    for (int i = 0; i < params.size(); i++) {
        content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "="
                + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
    }
    URL url = new URL(urlstr + "?" + content.substring(1));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.connect();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:edu.emory.library.viaf.ViafClient.java

/**
 * Query the VIAF AutoSuggest API to get suggestions matches for
 * a user-specified search term.  Returns an empty list if
 * no matches were found or if there was an error either making
 * the request or parsing the response.// ww  w  .ja v a2s  .c  o  m
 *
 * @param term  search term
 * @return      list of ViafResource
 */
public static List<ViafResource> suggest(String term) throws Exception {

    String uri = String.format("%s/AutoSuggest?query=%s", baseUrl, URLEncoder.encode(term, "UTF-8"));
    String result = EULHttpUtils.readUrlContents(uri);
    // todo: handle (at least log) http exceptions here

    List<ViafResource> resources = new ArrayList<ViafResource>();

    try {
        // parse the JSON and initialize a list of ViafResource objects
        // viaf autosuggest returns  in json format, with a list of results
        JSONObject json = (JSONObject) new JSONParser().parse(result);
        JSONArray jsonArray = (JSONArray) json.get("result");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = (JSONObject) jsonArray.get(i);

            // initialize a ViafResource for each result, using the viaf id and term
            // results may also include the following identifiers:
            //   lc, dnb, bnf, bne, nkc, nlilat, nla
            ViafResource vr = new ViafResource((String) obj.get("viafid"), (String) obj.get("term"));
            resources.add(vr);
        }

    } catch (Exception e) {
        // json parsing error - should just result in any empty resource list
        // TODO: log the error ?
    }
    return resources;
}