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:org.fcrepo.it.FusekiIT.java

private static HttpResponse queryFuseki(final String query) throws IOException {
    final String queryUrl = getFusekiBaseUrl() + "/test/query?query=" + URLEncoder.encode(query, "UTF-8")
            + "&default-graph-uri=&output=csv&stylesheet=";
    return client.execute(new HttpGet(queryUrl));
}

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

@Reflection
public static ArrayList<Lyrics> search(String query) {
    ArrayList<Lyrics> results = new ArrayList<>();
    query = query + " song";
    query = Normalizer.normalize(query, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+",
            "");//  w  ww . j a  v a 2 s .  c om
    try {
        URL queryURL = new URL(String.format(baseSearchUrl, URLEncoder.encode(query, "UTF-8")));
        Document searchpage = Jsoup.connect(queryURL.toExternalForm()).get();
        Elements searchResults = searchpage.getElementsByClass("Results");
        if (searchResults.size() >= 1) {
            searchResults = searchResults.get(0).getElementsByClass("result");
            for (Element searchResult : searchResults) {
                String[] tags = searchResult.getElementsByTag("h1").text().split(":");
                if (tags.length != 2)
                    continue;
                String url = searchResult.getElementsByTag("a").attr("href");
                Lyrics lyrics = new Lyrics(SEARCH_ITEM);
                lyrics.setArtist(tags[0]);
                lyrics.setTitle(tags[1]);
                lyrics.setURL(url);
                lyrics.setSource(domain);
                results.add(lyrics);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return results;
}

From source file:dal.arris.RequestArrisAlter.java

public RequestArrisAlter(Integer deviceId, Autenticacao autenticacao, String frequency)
        throws UnsupportedEncodingException, IOException {
    Autenticacao a = AuthFactory.getEnd();
    String auth = a.getUser() + ":" + a.getPassword();
    String url = a.getLink() + "capability/execute?capability="
            + URLEncoder.encode("\"getLanWiFiInfo\"", "UTF-8") + "&deviceId=" + deviceId + "&input="
            + URLEncoder.encode(frequency, "UTF-8");

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);//ww  w.  j  av a  2s.  com
    cm.setDefaultMaxPerRoute(1);
    HttpHost localhost = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    // Cookies
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(globalConfig).build();

    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
    String authHeader = "Basic " + new String(encodedAuth);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        httpget.setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
        httpget.setHeader("Cookie", "JSESSIONID=aaazqNDcHoduPbavRvVUv; AX-CARE-AGENTS-20480=HECDMIAKJABP");

        RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .build();

        HttpGet httpGet = new HttpGet("/");
        httpGet.setConfig(localConfig);

        //            httpget.setHeader(n);
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                    }
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
            for (Header allHeader : response.getAllHeaders()) {
                System.out.println("Nome: " + allHeader.getName() + " Valor: " + allHeader.getValue());
            }
        }
    } finally {
        httpclient.close();
    }
    httpclient.close();
}

From source file:de.micromata.genome.util.types.Converter.java

/**
 * Encode url param.//from w  w w.j ava2  s.c  o m
 *
 * @param value the value
 * @return the string
 */
public static String encodeUrlParam(String value) {
    if (StringUtils.isEmpty(value) == true) {
        return "";
    }

    try {
        return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

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

@Override
public String resource() {
    String encodedPath = path;/*from  w w  w  . j  av  a 2 s .co m*/
    try {
        encodedPath = URLEncoder.encode(path, "UTF-8");
    } catch (UnsupportedEncodingException e) {
    }
    StringBuilder builder = new StringBuilder("/job/").append(id).append("/dir?path=").append(encodedPath);
    return builder.toString();
}

From source file:net.a2bsoft.buss.http.SendQuery.java

public static String sendQuery(String query) {

    try {/*w w w  .  j a va 2s . co  m*/
        query = URLEncoder.encode(query, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return e.getMessage();
    }
    URL url = null;
    try {
        url = new URL(
                "http://www.atb.no/xmlhttprequest.php?service=routeplannerOracle.getOracleAnswer&question="
                        + query);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    String result = null;
    HttpParams my_httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(my_httpParams, 30000);
    HttpConnectionParams.setSoTimeout(my_httpParams, 30000);
    HttpClient client = new DefaultHttpClient(my_httpParams);
    HttpGet get = new HttpGet(url.toString());
    HttpResponse resp;

    try {
        resp = client.execute(get);
        InputStream data = resp.getEntity().getContent();
        result = new BufferedReader(new InputStreamReader(data)).readLine();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return sendQueryBusstuc(query);
        //         return e.getMessage();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return sendQueryBusstuc(query);
        //         return e.getMessage();
    }

    return result;
}

From source file:net.sourceforge.jwbf.actions.mw.util.GetEnvironmentVars.java

/**
 * //from w w  w  .j  a v a 2s . co  m
 * @param name of article
 * @param tab ref on a tabel with inner values
 * @param login a
 */
public GetEnvironmentVars(final String name, Hashtable<String, String> tab, LoginData login) {
    String uS = "";
    this.tab = tab;
    try {
        uS = "/index.php?title=" + URLEncoder.encode(name, MediaWikiBot.CHARSET) + "&action=edit&dontcountme=s";
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    msgs.add(new GetMethod(uS));
}

From source file:com.cmri.bpt.common.util.EncodeUtil.java

/**
 * URL ?, EncodeUTF-8.//from w ww.  j  av  a  2s.  com
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw ExceptionUtil.asUnChecked(e);
    }
}

From source file:org.acra.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * //w ww.j  av a2  s.  co m
 * @param parameters
 * @param url
 * @throws UnsupportedEncodingException
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
static void doPost(Map<?, ?> parameters, URL url)
        throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException {

    URLConnection cnx = getConnection(url);

    // Construct data
    StringBuilder dataBfr = new StringBuilder();
    Iterator<?> iKeys = parameters.keySet().iterator();
    while (iKeys.hasNext()) {
        if (dataBfr.length() != 0) {
            dataBfr.append('&');
        }
        String key = (String) iKeys.next();
        dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=')
                .append(URLEncoder.encode((String) parameters.get(key), "UTF-8"));
    }
    // POST data
    cnx.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream());
    Log.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

    Log.d(LOG_TAG, "Reading response");
    BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

    String line;
    while ((line = rd.readLine()) != null) {
        Log.d(LOG_TAG, line);
    }
    rd.close();
}

From source file:jp.terasoluna.fw.web.struts.actions.DownloadFileNameEncoderImpl.java

/**
 * _E??[hwt@CGR?[h?B/*w w w .  j a v a2  s.  co  m*/
 *
 * @param original ?B
 * @return GR?[h??B
 */
public String encode(String original, HttpServletRequest request, HttpServletResponse response) {
    // nullnullp?B
    if (original == null) {
        return null;
    }

    try {
        return URLEncoder.encode(original, AbstractDownloadObject.DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException e) {
        // ??AO???s?B
        if (log.isWarnEnabled()) {
            log.warn(AbstractDownloadObject.DEFAULT_CHARSET + " is not supported encoding", e);
        }
        return original;
    }
}