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.foglyn.fogbugz.Utils.java

static String urlEncode(String s) {
    try {/*ww  w . j  a va2  s. c o m*/
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Cannot encode to UTF-8? Whoops...", e);
    }
}

From source file:com.zaa.WeatherLoad.java

public void Load() {
    HttpURLConnection lv_connection = null;
    try {//from   w  w  w  . j  av a 2 s . c  o  m
        City.InitCity();
        String lv_name, lv_dt, lv_encoding, lv_response;
        Set lt_keys = Cache.gv_city.keySet();
        Iterator lv_iterator = lt_keys.iterator();
        JSONArray lv_json_array, lv_json_weather;
        JSONObject lv_json, lv_json_response, lv_json_weather_row, lv_json_temp;
        City lv_city;
        CityTemp lv_city_temp;
        int lv_resp_code;
        InputStream lv_in_stream;
        Hashtable lv_city_temp_col;
        while (lv_iterator.hasNext()) {
            lv_name = lv_iterator.next().toString();
            lv_city_temp_col = (Hashtable) Cache.gv_city_temp.get(lv_name);
            lv_connection = (HttpURLConnection) new URL("http://api.openweathermap.org/data/2.5/weather?q="
                    + URLEncoder.encode(lv_name, "utf-8") + "&units=metric").openConnection();
            lv_connection.setConnectTimeout(30000);
            lv_connection.setReadTimeout(30000);
            lv_connection.setDoOutput(true);
            lv_connection.setDoInput(true);
            lv_connection.setRequestMethod("GET");
            lv_connection.setRequestProperty("Accept-Encoding", "gzip");
            lv_resp_code = lv_connection.getResponseCode();
            lv_in_stream = new BufferedInputStream(lv_connection.getInputStream(), 8192);
            lv_encoding = lv_connection.getHeaderField("Content-Encoding");
            if (lv_encoding != null && lv_encoding.equalsIgnoreCase("gzip")) {
                lv_in_stream = new GZIPInputStream(lv_in_stream);
            }
            lv_response = convertStreamToString(lv_in_stream);
            lv_json_response = new JSONObject(lv_response);
            if (lv_json_response.getString("cod").equals("200")) {
                lv_city = (City) Cache.gv_city.get(lv_name);
                lv_json = lv_json_response.getJSONObject("main");
                lv_city.SetTemp(lv_json.getString("temp"));
                lv_city.SetPressure(lv_json.getString("pressure"));
                lv_city.SetHumidity(lv_json.getString("humidity"));
                lv_json = lv_json_response.getJSONObject("wind");
                lv_city.SetWindSpeed(lv_json.getString("speed"));
                lv_json_weather = lv_json_response.getJSONArray("weather");
                if (lv_json_weather != null) {
                    lv_json_weather_row = (JSONObject) lv_json_weather.get(0);
                    lv_city.SetIcon(lv_json_weather_row.getString("icon").substring(0, 2));
                }
                lv_city.Save();
            }
            lv_connection.disconnect();
            lv_connection = (HttpURLConnection) new URL(
                    "http://api.openweathermap.org/data/2.5/forecast/daily?q="
                            + URLEncoder.encode(lv_name, "utf-8") + "&units=metric&cnt=7").openConnection();
            lv_connection.setConnectTimeout(30000);
            lv_connection.setReadTimeout(30000);
            lv_connection.setDoOutput(true);
            lv_connection.setDoInput(true);
            lv_connection.setRequestMethod("GET");
            lv_connection.setRequestProperty("Accept-Encoding", "gzip");
            lv_resp_code = lv_connection.getResponseCode();
            lv_in_stream = new BufferedInputStream(lv_connection.getInputStream(), 8192);
            lv_encoding = lv_connection.getHeaderField("Content-Encoding");
            if (lv_encoding != null && lv_encoding.equalsIgnoreCase("gzip")) {
                lv_in_stream = new GZIPInputStream(lv_in_stream);
            }
            lv_response = convertStreamToString(lv_in_stream);
            lv_json_response = new JSONObject(lv_response);
            if (lv_json_response.getString("cod").equals("200")) {
                CityTemp.DeleteCityTemp(lv_name);
                lv_json_array = lv_json_response.getJSONArray("list");
                if (lv_json_array != null) {
                    for (int i = 0; i < lv_json_array.length(); i++) {
                        lv_json = (JSONObject) lv_json_array.get(i);
                        lv_dt = lv_json.getString("dt");
                        lv_city_temp = (CityTemp) lv_city_temp_col.get(lv_dt);
                        if (lv_city_temp == null) {
                            lv_city_temp = new CityTemp(lv_name, lv_dt);
                            lv_city_temp_col.put(lv_dt, lv_city_temp);
                        }
                        lv_json_weather = lv_json.getJSONArray("weather");
                        if (lv_json_weather != null) {
                            lv_json_weather_row = (JSONObject) lv_json_weather.get(0);
                            lv_city_temp.SetIcon(lv_json_weather_row.getString("icon").substring(0, 2));
                        }
                        lv_json_temp = lv_json.getJSONObject("temp");
                        lv_city_temp.SetTempDay(lv_json_temp.getString("day"));
                        lv_city_temp.SetTempNight(lv_json_temp.getString("night"));
                        lv_city_temp.Save();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        gv_handler.sendEmptyMessage(Weather.NO_NET);
    } finally {
        if (lv_connection != null) {
            lv_connection.disconnect();
        }
    }
    gv_handler.sendEmptyMessage(Weather.LOAD_OK);
}

From source file:com.ihandy.quote_core.serverpage.picc.XubaoSearchPage.java

@Override
public String doRequest(Request request) {
    String html = null;/*from w  w w  . j  a  va2s . co  m*/
    String url = request.getUrl();
    // url=url+"?pageSize=10&pageNo=1&prpCrenewalVo.licenseNo=%BE%A9P55M11&prpCrenewalVo.licenseType=02";
    // url=url+"?pageSize=10&pageNo=1";
    Map paraMap = request.getRequestParam();

    if (null != paraMap) {
        Set<String> key = paraMap.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String keyName = (String) it.next();
            String keyValue = paraMap.get(keyName).toString();
            if (keyName.equals("prpCrenewalVo.licenseNo")) {
                try {
                    keyValue = URLEncoder.encode(keyValue, "GBK");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                paraMap.put(keyName, keyValue);
            }
        }
    }

    String param = StringBaseUtils.Map2GetParam(paraMap);
    url = url + "?" + param;
    //  Map map = HttpsUtil.sendPost(url,param,super.piccSessionId);
    //  Map map = HttpsUtil.sendPost(url,param,"BOCINS_prpall_Cookie=pr2GX9vBshvQ0QyF157YJvTzH5JZJxzKwd5lHctTTdPXzWwnzjBp!-1432707418; JSESSIONID=4F19X8VTnvMP7cr5hHS1BJPVcmtkFJTLyQnQXV2K19HFCyg2d2vP!16969568");
    // Map map = HttpsUtil.sendPost(url,param,"BOCINS_prpall_Cookie=pr2GX9vBshvQ0QyF157YJvTzH5JZJxzKwd5lHctTTdPXzWwnzjBp!-1432707418; JSESSIONID=4F19X8VTnvMP7cr5hHS1BJPVcmtkFJTLyQnQXV2K19HFCyg2d2vP!16969568");
    Map map = HttpsUtil.sendGet(url, super.piccSessionId, "UTF-8");

    html = map.get("html").toString();
    return html;

}

From source file:org.opendatakit.provider.FormsProviderUtils.java

/**
 * Safely encode a value known to be a string for inclusion in the auxillaryHash
 * @param unquotedStringValue an unencoded string
 * @return that string but urlencoded/*  ww w  . j  av a  2s .  co m*/
 */
public static String encodeFragmentUnquotedStringValue(String unquotedStringValue)
        throws UnsupportedEncodingException {

    return URLEncoder.encode(unquotedStringValue, ApiConstants.UTF8_ENCODE).replace("+", URL_ENCODED_SPACE);
}

From source file:connector.ISConnector.java

public static JSONObject validateLogin(String email, String password) {
    JSONObject response = null;//from   www. ja v  a2  s. c o  m
    try {
        String utf8 = java.nio.charset.StandardCharsets.UTF_8.name();
        String query = String.format("email=%s&password=%s", URLEncoder.encode(email, utf8),
                URLEncoder.encode(password, utf8));
        response = processRequest("/login", query.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

From source file:com.intuit.tank.http.BaseRequestHandler.java

public static String getQueryString(Map<String, String> urlVariables) {

    StringBuilder queryString = new StringBuilder();

    // Set the query string
    if (urlVariables != null) {
        if (!urlVariables.isEmpty()) {

            queryString.append("?");

            // Set<Map.Entry<String, String>> set = urlVariables.entrySet();
            // Iterator<Map.Entry<String, String>> iterator =
            // set.iterator();
            for (Entry<String, String> entry : urlVariables.entrySet()) {
                try {
                    StringBuilder nvp = new StringBuilder();
                    nvp.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    if (entry.getValue() != null) {
                        nvp.append("=");
                        nvp.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                    }//from  w ww . j  a  va2  s.co m
                    nvp.append("&");
                    queryString.append(nvp.toString());

                } catch (Exception ex) {
                    logger.warn(LogUtil.getLogMessage("Unable to set query string value: " + ex.getMessage(),
                            LogEventType.System));
                }
            }
        }
    }

    // Remove the last &
    String reqQueryString = "";
    if (queryString.length() > 0) {
        if (queryString.charAt(queryString.length() - 1) == '&')
            reqQueryString = queryString.deleteCharAt(queryString.length() - 1).toString();
        else
            reqQueryString = queryString.toString();
    }

    return reqQueryString;
}

From source file:it.polito.tellmefirst.enhancer.BBCEnhancer.java

public String createURL(String URI, String API_KEY) {
    String result = "";
    try {//from www. ja  va2 s.  co m
        result = BBC_API + URLEncoder.encode(URI, "UTF-8") + "&api_key=" + API_KEY;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:edu.cornell.mannlib.semservices.service.impl.LCSHService.java

@Override
public List<Concept> getConcepts(String term) throws Exception {
    List<Concept> conceptList = new ArrayList<Concept>();
    String results = null;/*from w w w. ja v  a  2s. c  om*/
    String dataUrl = baseUri + "?q=" + URLEncoder.encode(term, "UTF-8")
            + "&q=cs%3Ahttp%3A%2F%2Fid.loc.gov%2Fauthorities%2Fsubjects" + "&format=XML";
    log.debug("dataURL " + dataUrl);

    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(dataUrl);

        BufferedReader in = new BufferedReader(new InputStreamReader(rss.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sw.write(inputLine);
        }
        in.close();

        results = sw.toString();
        log.debug(results);
    } catch (Exception ex) {
        log.error("error occurred in servlet", ex);
        return null;
    }

    if (StringUtils.isEmpty(results)) {
        return conceptList;
    }

    conceptList = processOutput(results);

    return conceptList;
}

From source file:com.ims.surport.security.Encodes.java

/**
 * URL ?, EncodeUTF-8./*from  w ww. ja v  a 2  s.  co  m*/
 */
public static String urlEncode(String part, String encode) {
    try {
        return URLEncoder.encode(part, StringUtils.isEmpty(encode) ? DEFAULT_URL_ENCODING : encode);
    } catch (UnsupportedEncodingException e) {
        throw Exceptions.unchecked(e);
    }
}

From source file:psiprobe.jsp.ParamToggleTag.java

@Override
public int doStartTag() throws JspException {
    boolean getSize = ServletRequestUtils.getBooleanParameter(pageContext.getRequest(), param, false);
    StringBuilder query = new StringBuilder();
    query.append(param).append("=").append(!getSize);
    String encoding = pageContext.getResponse().getCharacterEncoding();
    for (String name : Collections.list(pageContext.getRequest().getParameterNames())) {
        if (!param.equals(name)) {
            try {
                String value = ServletRequestUtils.getStringParameter(pageContext.getRequest(), name, "");
                String encodedValue = URLEncoder.encode(value, encoding);
                query.append("&").append(name).append("=").append(encodedValue);
            } catch (UnsupportedEncodingException e) {
                throw new JspException(e);
            }/*from www.  j a  va 2 s. c  om*/
        }
    }
    try {
        pageContext.getOut().print(query);
    } catch (IOException e) {
        logger.debug("Exception printing query string to JspWriter", e);
        throw new JspException(e);
    }
    return EVAL_BODY_INCLUDE;
}