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:be.geecko.openlauncher.net.SuggestionsTask.java

@Override
protected JSONArray doInBackground(String... strings) {
    String searchTerms = strings[0];
    try {/*from  w w  w  . ja  v  a2  s .co m*/
        searchTerms = URLEncoder.encode(searchTerms, "utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String url = String.format(
            "https://clients1.google.com/complete/search?output=toolbar&client=firefox&hl=%s&q=%s", "en", // fixme
            searchTerms);
    JSONArray result = null;
    try {
        JSONArray suggestionArray = new JSONArray(readUrl(url));
        result = suggestionArray.getJSONArray(1);
    } catch (JSONException | IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:es.deustotech.piramide.utils.tts.TextToSpeechWeb.java

private static synchronized void speech(final Context context, final String text, final String language) {
    executor.submit(new Runnable() {
        @Override// www . ja  va2  s. com
        public void run() {
            try {
                final String encodedUrl = Constants.URL + language + "&q="
                        + URLEncoder.encode(text, Encoding.UTF_8.name());
                final DefaultHttpClient client = new DefaultHttpClient();
                HttpParams params = new BasicHttpParams();
                params.setParameter("http.protocol.content-charset", "UTF-8");
                client.setParams(params);
                final FileOutputStream fos = context.openFileOutput(Constants.MP3_FILE,
                        Context.MODE_WORLD_READABLE);
                try {
                    try {
                        final HttpResponse response = client.execute(new HttpGet(encodedUrl));
                        downloadFile(response, fos);
                    } finally {
                        fos.close();
                    }
                    final String filePath = context.getFilesDir().getAbsolutePath() + "/" + Constants.MP3_FILE;
                    final MediaPlayer player = MediaPlayer.create(context.getApplicationContext(),
                            Uri.fromFile(new File(filePath)));
                    player.start();
                    Thread.sleep(player.getDuration());
                    while (player.isPlaying()) {
                        Thread.sleep(100);
                    }
                    player.stop();

                } finally {
                    context.deleteFile(Constants.MP3_FILE);
                }
            } catch (InterruptedException ie) {
                // ok
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.shangpin.utils.Encodes.java

/**
 * URL ?, EncodeUTF-8./*w w w.  jav a2 s  . c  o m*/
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw Exceptions.unchecked(e);
    } catch (NullPointerException e) {
        return null;
    }
}

From source file:com.dsh105.nexus.command.module.utility.IpInfoCommand.java

@Override
public boolean onCommand(CommandPerformEvent event) {
    String[] args = event.getArgs();
    if (args.length != 1 || (args[0].length() < 7)) {
        return false;
    }//from w w w. j  ava 2 s.c o m

    String url = null;

    try {
        url = API_URL + URLEncoder.encode(args[0], "UTF-8");

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    try {
        HttpResponse<JsonNode> resp = Unirest.get(url).asJson();

        if (resp.getCode() != 200) {
            event.errorWithPing("Unknown error occurred while executing command! Try again later...");
            return false;
        }

        StringBuilder builder = new StringBuilder();
        final JSONObject object = resp.getBody().getObject();
        String maps = "No maps available.";

        if (object.has("latitude")) {
            maps = "https://maps.google.com/maps?q=" + object.get("latitude") + "," + object.get("longitude");
        }

        String info = "Info for " + args[0] + ": ";
        builder.append(Colors.BOLD + info);

        if (object.has("country")) {
            builder.append("Country: ").append(Colors.BOLD + object.getString("country") + Colors.NORMAL)
                    .append(" ");
        }

        if (object.has("isp")) {
            builder.append("ISP: ").append(Colors.BOLD + object.getString("isp") + Colors.NORMAL).append(" ");
        }

        event.respondWithPing(builder.toString().trim() + " (" + URLShortener.shorten(maps) + ")");

    } catch (UnirestException e) {
        return false;
    }
    return true;
}

From source file:org.shredzone.cilla.plugin.social.IdenticaSocialHandler.java

/**
 * identi.ca//from w  ww  .j  a  v  a2  s.c  o  m
 */
@SocialBookmark(icon = "identica.png")
@Priority(11)
public String identicaSocialBookmark(@PageLink(shortened = true) String pageLink, @PageTitle String pageTitle) {
    String post = pageLink + " - " + pageTitle;

    if (post.length() > MAX_POST_LENGTH) {
        post = post.substring(0, MAX_POST_LENGTH);
    }

    try {
        return "http://identi.ca/notice/new?status_textarea=" + URLEncoder.encode(post, "utf-8");
    } catch (UnsupportedEncodingException ex) {
        throw new InternalError("no utf-8");
    }
}

From source file:com.aylien.textapi.HttpSender.java

public String post(String url, Map<String, String> parameters, Map<String, String> headers)
        throws IOException, TextAPIException {
    try {//w w  w.  jav a2  s  . co m
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        for (Map.Entry<String, String> header : headers.entrySet()) {
            connection.setRequestProperty(header.getKey(), header.getValue());
        }
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("User-Agent", USER_AGENT);

        StringBuilder payload = new StringBuilder();
        for (Map.Entry<String, String> e : parameters.entrySet()) {
            if (payload.length() > 0) {
                payload.append('&');
            }
            payload.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=')
                    .append(URLEncoder.encode(e.getValue(), "UTF-8"));
        }

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(payload.toString());
        writer.close();

        responseHeaders = connection.getHeaderFields();

        InputStream inputStream = connection.getResponseCode() == 200 ? connection.getInputStream()
                : connection.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        if (connection.getResponseCode() >= 300) {
            extractTextAPIError(response.toString());
        }

        return response.toString();
    } catch (MalformedURLException e) {
        throw new IOException(e);
    }
}

From source file:apm.common.utils.Encodes.java

/**
 * URL ?, EncodeUTF-8. //from w  w  w .  ja va  2 s.c  o m
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw Exceptions.unchecked(e);
    }
}

From source file:eu.eexcess.opensearch.querygenerator.OpensearchQuerygeneratorTest.java

@Test
public void toQuery_withSecureUserProfileKeywordsButNoLimit_expectPass() {

    SecureUserProfile userProfile = new SecureUserProfile();

    String keywordText = "some Text with special characters {[]}\\";
    userProfile.numResults = 0;/*from www .  ja v  a2  s.  c  om*/
    userProfile.contextKeywords = newDummyContextKeywords(7, keywordText);

    OpensearchQueryGenerator generator = new OpensearchQueryGenerator();
    String query = generator.toQuery(userProfile);

    try {
        assertTrue(query.contains(URLEncoder.encode(keywordText, CharEncoding.UTF_8)));
        assertTrue(query.contains(URLEncoder.encode(keywordText + "[1]", CharEncoding.UTF_8)));
        assertTrue(query.contains(URLEncoder.encode(keywordText + "[6]", CharEncoding.UTF_8)));
        assertFalse(query.contains(URLEncoder.encode(keywordText + "[7]", CharEncoding.UTF_8)));
        assertFalse(query.contains("&limit="));
        assertFalse(query.contains("limit"));
    } catch (UnsupportedEncodingException e) {
        assertTrue(false);
    }

}

From source file:com.aokyu.dev.pocket.http.HttpParameters.java

public String toEncodedParameter() throws UnsupportedEncodingException {
    StringBuilder builder = new StringBuilder();
    Set<Entry<String, Object>> entries = entrySet();
    boolean first = true;
    for (Entry<String, Object> entry : entries) {
        if (first) {
            first = false;//w w w.ja v  a2 s .c o m
        } else {
            builder.append("&");
        }
        String key = entry.getKey();
        Object value = entry.getValue();
        builder.append(key);
        builder.append("=");
        String valueAsString = value.toString();
        String encoded = URLEncoder.encode(valueAsString, "UTF-8");
        builder.append(encoded);
    }
    return builder.toString();
}

From source file:com.net.wx.util.Encodes.java

/**
 * URL ?, EncodeUTF-8./* ww  w  . ja  va 2  s  .  c om*/
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    }
}