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:it.reyboz.bustorino.backend.GTTJSONFetcher.java

@Override
@NonNull//from  ww w.j av  a 2  s  . c  o m
public Palina ReadArrivalTimesAll(String stopID, AtomicReference<result> res) {
    URL url;
    Palina p = new Palina(stopID);
    String routename;
    String bacino;
    String content;
    JSONArray json;
    int howManyRoutes, howManyPassaggi, i, j, pos; // il misto inglese-italiano  un po' ridicolo ma tanto vale...
    JSONObject thisroute;
    JSONArray passaggi;

    try {
        url = new URL("http://www.gtt.to.it/cms/index.php?option=com_gtt&task=palina.getTransiti&palina="
                + URLEncoder.encode(stopID, "utf-8") + "&realtime=true");
    } catch (Exception e) {
        res.set(result.PARSER_ERROR);
        return p;
    }

    content = networkTools.queryURL(url, res);
    if (content == null) {
        return p;
    }

    try {
        json = new JSONArray(content);
    } catch (JSONException e) {
        res.set(result.PARSER_ERROR);
        return p;
    }

    try {
        // returns [{"PassaggiRT":[],"Passaggi":[]}] for non existing stops!
        json.getJSONObject(0).getString("Linea"); // if we can get this, then there's something useful in the array.
    } catch (JSONException e) {
        res.set(result.EMPTY_RESULT_SET);
        return p;
    }

    howManyRoutes = json.length();
    if (howManyRoutes == 0) {
        res.set(result.EMPTY_RESULT_SET);
        return p;
    }

    try {
        for (i = 0; i < howManyRoutes; i++) {
            thisroute = json.getJSONObject(i);
            routename = thisroute.getString("Linea");
            try {
                bacino = thisroute.getString("Bacino");
            } catch (JSONException ignored) { // if "Bacino" gets removed...
                bacino = "U";
            }

            pos = p.addRoute(routename, thisroute.getString("Direzione"),
                    FiveTNormalizer.decodeType(routename, bacino));

            /*
             * Okay, this is just absurd.
             * The underground always has 4 non-real-time timetable entries; however, the first
             * two are old\stale\bogus, as they're in the past. The other two are exactly the
             * same ones that appear on the screens in the stations.
             */
            if (routename.equals("METRO")) {
                j = 2;
            } else {
                j = 0;
            }

            passaggi = thisroute.getJSONArray("PassaggiRT");
            howManyPassaggi = passaggi.length();
            for (; j < howManyPassaggi; j++) {
                p.addPassaggio(passaggi.getString(j).concat("*"), pos);
            }

            passaggi = thisroute.getJSONArray("Passaggi"); // now the non-real-time ones
            howManyPassaggi = passaggi.length();
            for (; j < howManyPassaggi; j++) {
                p.addPassaggio(passaggi.getString(j), pos);
            }
        }
    } catch (JSONException e) {
        res.set(result.PARSER_ERROR);
        return p;
    }

    p.sortRoutes();
    res.set(result.OK);
    return p;
}

From source file:org.ngrinder.script.controller.MyHttpServletRequestWrapperTest.java

@Test
public void testHandleRequest3() throws UnsupportedEncodingException {
    String testURI = "/hello/svnadmin/admin/";
    testURI = URLEncoder.encode(testURI, "UTF-8");

    HttpServletRequest req = new MockHttpServletRequest("GET", testURI);
    wrapper = new MyHttpServletRequestWrapper(req) {
        public String getRequestURI() {
            return "/hello/svn/admin/";
        }/*from  w  ww  . j a v a  2  s  .  c  o m*/

        @Override
        public String getContextPath() {
            return "/hello";
        }
    };
    String path = wrapper.getPathInfo();
    assertThat(path, is("/admin/%ED%95%9C%EA%B8%80"));
}

From source file:baggage.hypertoolkit.html.UrlParamEncoder.java

public String asUrl(Bag<String, String> bag) {
    StringBuilder url = new StringBuilder();
    if (bag.isEmpty()) {
        return "";
    }//from   ww  w  .  j  a  v  a 2 s  .c o  m

    url.append("?");
    for (String key : bag.keySet()) {
        Collection<String> values = bag.getValues(key);
        for (String value : values) {
            try {
                url.append(URLEncoder.encode(StringUtils.stripToEmpty(key), "UTF-8"));
                url.append("=");
                url.append(URLEncoder.encode(StringUtils.stripToEmpty(value), "UTF-8"));
                url.append("&");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }
    url.deleteCharAt(url.length() - 1);
    return url.toString();
}

From source file:org.wso2.identity.integration.test.entitlement.EntitlementSecurityTestCase.java

@BeforeClass(alwaysRun = true)
public void testInit() throws Exception {
    super.init();
    httpClient = HttpClientBuilder.create().build();
    value = "<script>alert(1);</script>";
    String encodedValue = URLEncoder.encode(value, "UTF-8");
    String temp = backendURL.replaceAll("services/",
            "carbon/policyeditor/prettyPrinter_ajaxprocessor.jsp?xmlString=");
    url = temp + encodedValue;/*w  ww  .j a va2  s.  com*/
}

From source file:io.github.retz.protocol.DownloadFileRequest.java

@Override
public String resource() {
    String encodedFile = file;/* w w w.j a v a2  s.  c om*/
    try {
        encodedFile = URLEncoder.encode(file, "UTF-8");
    } catch (UnsupportedEncodingException e) {
    }

    StringBuilder builder = new StringBuilder("/job/").append(id).append("/download").append("?path=")
            .append(encodedFile);

    return builder.toString();
}

From source file:com.geecko.QuickLyric.tasks.CoverArtLoader.java

@Override
protected String doInBackground(Object... objects) {
    Lyrics lyrics = (Lyrics) objects[0];
    lyricsViewFragment = (LyricsViewFragment) objects[1];
    String url = lyrics.getCoverURL();

    if (url == null) {
        try {/*from   w ww  . ja v a2s.c o  m*/
            String html = Net.getUrlAsString(new URL(String.format(
                    "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=%s&artist=%s&track=%s&format=json",
                    Keys.lastFM, URLEncoder.encode(lyrics.getArtist(), "UTF-8"),
                    URLEncoder.encode(lyrics.getTrack(), "UTF-8"))));
            JSONObject json = new JSONObject(html);
            url = json.getJSONObject("track").getJSONObject("album").getJSONArray("image").getJSONObject(2)
                    .getString("#text");
            if (url.contains("noimage"))
                url = null;
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }
    return url;
}

From source file:de.mpg.escidoc.services.aa.crypto.RSAEncoder.java

public static String rsaEncrypt(String string) throws Exception {
    StringWriter resultWriter = new StringWriter();
    byte[] bytes = string.getBytes("UTF-8");
    PublicKey pubKey = (PublicKey) readKeyFromFile(Config.getProperty("escidoc.aa.public.key.file"), true);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    int blockSize = 245;
    for (int i = 0; i < bytes.length; i += blockSize) {
        byte[] result = cipher.doFinal(bytes, i, (i + blockSize < bytes.length ? blockSize : bytes.length - i));
        if (i > 0) {
            resultWriter.write("&");
        }//from w  w w  .j  a v  a  2 s.c  o  m
        resultWriter.write("auth=");
        resultWriter.write(URLEncoder.encode(new String(Base64.encodeBase64(result)), "ISO-8859-1"));
    }
    return resultWriter.toString();

}

From source file:net.fenyo.mail4hotspot.web.GMailOAuthStep1Servlet.java

private String urlEncode(final String url) throws UnsupportedEncodingException {
    return URLEncoder.encode(url, "UTF-8");
}

From source file:com.domsplace.DomsCommandsXenforoAddon.Threads.XenforoUpdateThread.java

private String encode(String x) {
    try {//from   w  w w .  ja  va  2s. c om
        return URLEncoder.encode(x, "ISO-8859-1");
    } catch (UnsupportedEncodingException ex) {
        return x;
    }
}

From source file:com.shahnami.fetch.Controller.FetchMovies.java

public List<Movie> getBollyMovies(String query) {
    try {/*from   w ww.j a  va2  s.  co m*/
        Document doc;
        Elements searchDetails;
        String link;
        String title;
        String image = null;
        Elements linkAndTitles;
        Document movieDetails;
        double rating = 0;
        String magnetLink;
        String torrentFile;
        NumberFormat formatter;
        String output;
        if (query.equalsIgnoreCase("")) {
            //
        } else {
            doc = Jsoup.connect("https://1337x.to/search/" + URLEncoder.encode(query, "UTF-8") + "+hindi/1/")
                    .userAgent("Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.2) Gecko/20040803").get();
            searchDetails = doc.getElementsByClass("coll-1");
            for (Element e : searchDetails) {
                linkAndTitles = e.getElementsByTag("strong");
                for (Element e1 : linkAndTitles) {
                    link = "https://1337x.to" + e1.getElementsByTag("a").first().attr("href");
                    title = e1.getElementsByTag("a").first().html();
                    if (!link.contains("/mirror")) {
                        Movie m = new Movie();
                        m.setTitle(title.replace("<b>", "").replace("</b>", "").trim()); //.substring(0, 47)+ "..."
                        m.setLanguage("Hindi");
                        m.setUrl(link);
                        Pattern pattern = Pattern.compile(".*([\\s(]+[0-9]{4}[\\s)]+).*");
                        Matcher matcher = pattern.matcher(title);
                        while (matcher.find()) {
                            m.setYear(Integer
                                    .parseInt(matcher.group(1).replace("(", "").replace(")", "").trim()));
                        }
                        movieDetails = Jsoup.connect(link).get();
                        try {
                            image = movieDetails.getElementsByClass("moive-box").first().getElementsByTag("img")
                                    .first().attr("src");
                            rating = Float.parseFloat(
                                    movieDetails.getElementsByClass("rateing").first().getElementsByTag("i")
                                            .attr("style").split(":")[1].replace("%;", "").trim());
                        } catch (Exception ex) {
                            //
                        }
                        magnetLink = movieDetails.getElementsByClass("magnet").first().attr("href");
                        torrentFile = movieDetails.getElementsByClass("torrent").first().attr("href");
                        formatter = NumberFormat.getNumberInstance();
                        formatter.setMinimumFractionDigits(2);
                        formatter.setMaximumFractionDigits(2);
                        output = formatter.format(rating / 10);
                        rating = Double.parseDouble(output);
                        if (rating < 1) {
                            rating = 0;
                        }
                        m.setRating(rating);
                        m.setSmall_cover_image(image);
                        List<Torrent> torrents = new ArrayList<>();
                        Torrent t = new Torrent();
                        t.setUrl(magnetLink);
                        Torrent t2 = new Torrent();
                        t2.setUrl(torrentFile);
                        torrents.add(t);
                        torrents.add(t2);
                        m.setTorrents(torrents);
                        m.getTorrents().get(0).setSeeds(
                                Integer.valueOf(movieDetails.getElementsByClass("green").first().text()));
                        m.getTorrents().get(0).setPeers(
                                Integer.valueOf(movieDetails.getElementsByClass("red").first().text()));
                        m.setIsBollywood(true);
                        m.setSize(movieDetails.getElementsByClass("list").first().getElementsByTag("li").get(3)
                                .text().substring(10).trim());
                        _movies.add(m);
                    }
                }
                //String link = linkAndTitle.getElementsByAttribute("href").first().text();
                //System.out.println(link);
                //String title = linkAndTitle.getElementsByTag("b").text();
                //System.out.println(title);
            }
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FetchMovies.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FetchMovies.class.getName()).log(Level.SEVERE, null, ex);
    }
    return _movies;
}