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.ultrapower.eoms.common.plugin.ecside.util.ECSideUtils.java

    public static String encodeFileName(String fileName, String agent) throws UnsupportedEncodingException{
      String codedfilename = null;
      fileName=fileName.replaceAll("\n|\r", " ").trim();

      if (null != agent && -1 != agent.indexOf("MSIE")) {

         codedfilename = URLEncoder.encode(fileName, "UTF8");
//         String prefix = fileName.lastIndexOf(".") != -1 ? fileName
//            .substring(0, fileName.lastIndexOf(".")) : fileName;
//         String extension = fileName.lastIndexOf(".") != -1 ? fileName
//            .substring(fileName.lastIndexOf(".")) : "";
//         int limit = 150 - extension.length();
//         if (codedfilename.length() > limit) {
//            codedfilename = java.net.URLEncoder.encode(prefix.substring(0, Math.min(
//                  prefix.length(), limit / 9)), "UTF-8");
//            codedfilename = codedfilename + extension;
//         }//w  w w  . j  a  va 2  s.c  o m
      } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
         codedfilename = "=?UTF-8?B?"+(new String(Base64.encodeBase64(fileName.getBytes("UTF-8"))))+"?=";
      } else {
         codedfilename = fileName;
      }
      return codedfilename;
   }

From source file:com.dubsar_dictionary.Dubsar.model.Autocompleter.java

/**import java.net.URLEncoder;
        /*w  w  w .j a  va 2 s. co m*/
 * Request suggestions for the specified term.
 * @param term the term, as typed by the user so far
 */
public Autocompleter(String term) {
    mTerm = new String(term);

    // DEBT: Take from strings file
    try {
        mPath = new String("/os?term=") + URLEncoder.encode(mTerm, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        setErrorMessage(e.getMessage());
    }
}

From source file:spring.travel.site.auth.CookieEncoder.java

private String urlEncode(String arg) {
    try {//from w w w  . j av a2 s  .  c o m
        return URLEncoder.encode(arg, "UTF-8");
    } catch (UnsupportedEncodingException bogus) {
        return arg;
    }
}

From source file:com.itwizard.mezzofanti.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*from  w w w.  ja  va2s .c om*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d("TEST", "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d("TEST", "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.beust.android.translate.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate.//  w  w w  .ja  v  a 2s  .  c om
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TranslateService.TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TranslateService.TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.woopra.tracking.android.WoopraPing.java

public WoopraPing(String domain, String cookie, WoopraClientInfo clientInfo, long idleTimeout) {
    StringBuilder pingUrlBuilder = new StringBuilder();
    try {//from  www.  ja  v a 2s.c o m
        pingUrlBuilder.append(W_PING_ENDPOINT).append("?host=").append(URLEncoder.encode(domain, "UTF-8"))
                .append("&cookie=").append(URLEncoder.encode(cookie, "UTF-8")).append("&screen=")
                .append(clientInfo.getScreenResolution()).append("&language=")
                .append(URLEncoder.encode(clientInfo.getLanguage(), "UTF-8")).append("&browser=")
                .append(URLEncoder.encode(clientInfo.getClient(), "UTF-8"))
                .append("&app=android&response=xml&timeout=").append(idleTimeout);
    } catch (UnsupportedEncodingException e) {
        // eat it and will never happen
    }
    this.pingUrl = pingUrlBuilder.toString();
    this.clientInfo = clientInfo;
}

From source file:com.brett.http.geo.baidu.GeoRequestHttpClient.java

public static JsonNode geoAcquire(String city) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {//  www. ja  v a 2  s.c o m

        String address = URLEncoder.encode(city, "utf-8");

        String url = "http://api.map.baidu.com/geocoder/v2/?address={address}&output=json&ak=E4805d16520de693a3fe707cdc962045";

        url = url.replaceFirst("\\{address\\}", address);

        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer",
                "http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(HtmlDecoder.decode(responseBody));
        System.out.println(responseBody);

        System.out.println("----------------------------------------");

        ObjectMapper mapper = new ObjectMapper();
        mapper.readValue(responseBody, AddressCoord.class);
        //      JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1));

        // {"status":0,"result":{"location":{"lng":116.30783584945,"lat":40.056876296398},"precise":1,"confidence":80,"level":"\u5546\u52a1\u5927\u53a6"}}
        JsonNode root = mapper.readTree(responseBody);

        System.out.println("result : " + city + " = " + root.get("result"));

        return root;

    } finally {
        httpclient.close();
    }
}

From source file:com.fastbootmobile.encore.api.musicbrainz.MusicBrainzClient.java

/**
 * Retrieves the album information from MusicBrainz. This method is synchronous and must be
 * called from a Thread!//from w  w  w .j av  a 2 s  .  c o m
 * @param artist The name of the artist. Must be filled.
 * @param album The name of the album. May be empty.
 * @return An {@link com.fastbootmobile.encore.api.musicbrainz.AlbumInfo} filled with the information
 * from musicbrainz, or null in case of error
 */
public static AlbumInfo[] getAlbum(String artist, String album) throws RateLimitException {
    if (mAlbumInfoCache.containsKey(Pair.create(artist, album))) {
        return mAlbumInfoCache.get(Pair.create(artist, album));
    }

    if (artist == null && album == null) {
        return null;
    }

    try {
        String query = "";
        if (artist != null) {
            query += URLEncoder.encode("artist:\"" + artist + "\"", "UTF-8");
        }
        if (album != null && !album.isEmpty()) {
            query += URLEncoder.encode(" AND release:\"" + album + "\"", "UTF-8");
        }
        JSONObject object = JsonGet.getObject(MAIN_EP + "/release/", "fmt=json&query=" + query, true);

        if (object.has("releases")) {
            JSONArray releases = object.getJSONArray("releases");
            final int releasesCount = releases.length();
            if (releasesCount > 0) {
                AlbumInfo[] infoArray = new AlbumInfo[releasesCount];

                for (int i = 0; i < releasesCount; i++) {
                    AlbumInfo info = new AlbumInfo();

                    JSONObject release = releases.getJSONObject(i);

                    info.id = release.getString("id");
                    try {
                        info.track_count = release.getInt("track-count");
                    } catch (JSONException e) {
                        // No track count info, too bad
                        info.track_count = 0;
                    }

                    infoArray[i] = info;
                }

                mAlbumInfoCache.put(Pair.create(artist, album), infoArray);
                return infoArray;
            }
        } else if (object.has("error")) {
            Log.w(TAG, "Rate limited by the API, will retry later");
            throw new RateLimitException();
        }

        // AlbumArtCache will retry with something else if needed
        mAlbumInfoCache.put(Pair.create(artist, album), null);
        return null;
    } catch (IOException e) {
        Log.e(TAG, "Unable to get album info (rate limit?)", e);
        throw new RateLimitException();
    } catch (JSONException e) {
        // May happen due to an API error, e.g. error 502
        Log.e(TAG, "JSON error while parsing album info", e);
        throw new RateLimitException();
    }
}

From source file:com.aperigeek.facebook.fmap.fbapi.FbClientImpl.java

public long getUserId() throws FbException {
    try {/*from  www. ja  va  2  s .  c o m*/
        String fburl = "https://graph.facebook.com/me?access_token="
                + URLEncoder.encode(accessToken, FB_CHARSET);

        URL url = new URL(fburl);

        InputStream urlIn = url.openStream();
        InputStreamReader reader = new InputStreamReader(urlIn);

        JSONTokener tokener = new JSONTokener(reader);
        JSONObject me = (JSONObject) tokener.nextValue();

        urlIn.close();

        return me.getLong("id");
    } catch (IOException ex) {
        throw new FbException("Unsupported I/O error", ex);
    } catch (JSONException ex) {
        throw new FbException("API error: invlaid JSON", ex);
    }
}

From source file:io.fabric8.maven.docker.access.util.RequestUtil.java

@SuppressWarnings("deprecation")
public static String encode(String param) {
    try {//from  w w  w . j  av  a2  s  .co  m
        return URLEncoder.encode(param, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // wont happen
        return URLEncoder.encode(param);
    }
}