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.taobao.ad.easyschedule.commons.utils.MailUtil.java

/**
 * ??//from   w ww. j a va 2 s.c  o  m
 * 
 * @param list
 *            ?
 * @param subject
 * @param content
 */
public static void sendMail(String list, String subject, String content) {

    if ("false".equals(Constants.SENDMAIL) || StringUtils.isEmpty(list) || StringUtils.isEmpty(subject)) {
        return;
    }
    try {
        String command = Constants.MAIL_SEND_COMMAND;
        String strSubject = subject;
        if (subject.getBytes().length > 50) {
            strSubject = StringUtil.bSubstring(subject, 49);
        }
        String strContent = content;
        if (content.getBytes().length > 2046) {
            strContent = StringUtil.bSubstring(content, 2045);
        }
        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("MailUtil.sendMail 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("MailUtil.sendMail", e);
    }
}

From source file:com.elega9t.commons.geo.impl.HostIpDotInfoGeoLocationProvider.java

@Override
public GeoLocationInfo lookup(String ip) throws IOException {
    URL url = new URL("http://api.hostip.info/get_json.php?ip=" + URLEncoder.encode(ip, "UTF-8"));
    URLConnection connection = url.openConnection();
    connection.connect();//ww w.ja  va  2  s .co m
    InputStream inputStream = connection.getInputStream();
    String json = IOUtilities.toString(inputStream);
    inputStream.close();
    try {
        JSONObject object = new JSONObject(json);
        return new GeoLocationInfo(object.getString("ip"), object.getString("country_name"),
                object.getString("country_code"), object.getString("city"));
    } catch (JSONException e) {
        throw new IOException(e);
    }
}

From source file:com.googlecode.batchfb.util.StringUtils.java

/**
 * Masks the useless checked exception from URLEncoder.encode()
 *///from w  w w  . j  a  v  a2s.c  o  m
public static String urlEncode(String string) {
    try {
        return URLEncoder.encode(string, "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:at.tugraz.sss.serv.SSUri.java

public static Boolean isURI(final String string) throws Exception {

    //    URIUtil.encodeQuery(string)
    //    new URL(uriString); //import java.net.URL;
    try {//from w w  w. ja v  a2  s . c o m
        if (string == null) {
            return false;
        }

        try {
            new URL(string);
            java.net.URI.create(string);
            URLEncoder.encode(string, SSEncodingU.utf8.toString());

            if (string.length() > 250) {
                SSLogU.warn("uri too long (> 250 chars) to be stored in sss");
                return false;
            }

        } catch (Exception error) {
            return false;
        }

        return true;
    } catch (Exception error) {
        throw error;
    }
}

From source file:br.pub.tradutor.TradutorController.java

/**
 * Mtodo utilizado para traduo utilizando o Google Translate
 *
 * @param text Texto a ser traduzido/*from  w ww. java 2s  .c  o m*/
 * @param from Idioma de origem
 * @param to Idioma de destino
 * @return Texto traduzido (no idioma destino)
 * @throws IOException
 */
public static String translate(String text, String from, String to) throws IOException {
    //Faz encode de URL, para fazer escape dos valores que vo na URL
    String encodedText = URLEncoder.encode(text, "UTF-8");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //Mtodo GET a ser executado
    HttpGet httpget = new HttpGet(String.format(TRANSLATOR, encodedText, from, to));

    //Faz a execuo
    HttpResponse response = httpclient.execute(httpget);

    //Busca a resposta da requisio e armazena em String
    String returnContent = EntityUtils.toString(response.getEntity());

    //Desconsidera tudo depois do primeiro array
    returnContent = returnContent.split("\\],\\[")[0];

    //StringBuilder que sera carregado o retorno
    StringBuilder translatedText = new StringBuilder();

    //Verifica todas as tradues encontradas, e junta todos os trechos
    Matcher m = RESULTS_PATTERN.matcher(returnContent);
    while (m.find()) {
        translatedText.append(m.group(1).trim()).append(' ');
    }

    //Retorna
    return translatedText.toString().trim();

}

From source file:com.ct855.util.HttpsClientUtil.java

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }//from ww  w  .  j a  va2s  .  com
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:xqpark.ParkApi.java

/**
 * API?// w ww  .ja  v  a 2  s  . c  o m
 * @param ?url
 * @return APIJSON?
 * @throws JSONException
 * @throws IOException 
 * @throws ParseException 
 */
public static JSONObject loadJSON(String url) throws JSONException {
    StringBuilder json = new StringBuilder();
    try {
        URLEncoder.encode(url, "UTF-8");
        URL urlObject = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) urlObject.openConnection();

        uc.setDoOutput(true);//  URL 
        uc.setDoInput(true);//  URL 
        uc.setUseCaches(false);
        uc.setRequestMethod("POST");

        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject responseJson = new JSONObject(json.toString());
    return responseJson;
}

From source file:Main.java

public static String encodeToURL(String s, String defaultString) {
    String encoded = defaultString;
    if (s != null && s.length() > 0) {
        try {//from ww w  . j  a va2s .c om
            encoded = URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("XJUtils:encodeToURL exception: " + e);
        }
    }
    return encoded;
}

From source file:com.geecko.QuickLyric.lyrics.Genius.java

public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+",
            "");//from w  w w  .  j a  va  2s. co  m
    JSONObject response = null;
    try {
        URL queryURL = new URL(
                String.format("http://api.genius.com/search?q=%s", URLEncoder.encode(query, "UTF-8")));
        response = new JSONObject(Net.getUrlAsString(queryURL));
    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }

    try {
        if (response == null || response.getJSONObject("meta").getInt("status") != 200)
            return results;
        JSONArray hits = response.getJSONObject("response").getJSONArray("hits");

        int processed = 0;
        while (processed < hits.length()) {
            JSONObject song = hits.getJSONObject(processed).getJSONObject("result");
            String artist = song.getJSONObject("primary_artist").getString("name");
            String title = song.getString("title");
            String url = "http://genius.com/songs/" + song.getInt("id");
            Lyrics l = new Lyrics(Lyrics.SEARCH_ITEM);
            l.setArtist(artist);
            l.setTitle(title);
            l.setURL(url);
            l.setSource("Genius");
            results.add(l);
            processed++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return results;
}

From source file:com.iterzp.momo.utils.WebUtils.java

/**
 * cookie/*from   w  w w  . j av  a 2  s  .  c o m*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param value
 *            cookie
 * @param maxAge
 *            (??: )
 * @param path
 *            
 * @param domain
 *            
 * @param secure
 *            ??
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, Integer maxAge, String path, String domain, Boolean secure) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        name = URLEncoder.encode(name, "UTF-8");
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(name, value);
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        if (secure != null) {
            cookie.setSecure(secure);
        }
        response.addCookie(cookie);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}