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.lexicalintelligence.search.SearchRequest.java

public SearchResponse execute() {
    Reader reader = null;//from  ww w  . j  av a  2 s . c o  m
    SearchResponse searchResponse = new SearchResponse(true);
    try {
        HttpResponse response = client.getHttpClient()
                .execute(new HttpGet(client.getUrl() + PATH + "?prefix=" + URLEncoder.encode(query, "UTF-8")));
        reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8);
        List<String> items = client.getObjectMapper().readValue(reader, new TypeReference<List<String>>() {
        });
        searchResponse.setItems(items);
    } catch (Exception e) {
        searchResponse = new SearchResponse(false);
        log.error(e);
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            log.error(e);
        }
    }
    return searchResponse;
}

From source file:com.poscoict.license.web.controller.DownloadView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) model.get("downloadFile");

    File file = (File) map.get("file");
    String fileName = "";
    if (map.get("fileName") != null)
        fileName = (String) map.get("fileName");
    else//from  w  w w  .  j  a  va  2 s .com
        fileName = file.getName();

    response.setContentType(getContentType());
    response.setContentLength((int) file.length());

    String header = getBrowser(request);

    if (header.contains("MSIE")) {

        String docName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

        response.setHeader("Content-Disposition", "attachment;filename=" + docName + ";");

    } else if (header.contains("Firefox")) {

        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");

    } else if (header.contains("Opera")) {

        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");

    } else if (header.contains("Chrome")) {

        String docName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + docName + "\"");

    }

    response.setHeader("Content-Type", "application/octet-stream");

    response.setHeader("Content-Transfer-Encoding", "binary;");

    response.setHeader("Pragma", "no-cache;");

    response.setHeader("Expires", "-1;");

    OutputStream out = response.getOutputStream();
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);
        FileCopyUtils.copy(fis, out);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }
    }
    out.flush();
}

From source file:org.elegosproject.romupdater.DownloadManager.java

public static boolean sendAnonymousData() {
    String link = "http://www.elegosproject.org/android/upload.php";
    String data;// w w w.  java2 s . c  o  m

    SharedData shared = SharedData.getInstance();
    String romName = shared.getRepositoryROMName();
    String romVersion = shared.getDownloadVersion();
    String romPhone = shared.getRepositoryModel();
    String romRepository = shared.getRepositoryUrl();

    if (romName.equals("") || romVersion.equals("") || romPhone.equals("") || romRepository.equals("")) {
        Log.e(TAG, "Internal error - missing system variables.");
        return false;
    }

    if (!checkHttpFile(link))
        return false;
    try {
        data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(romPhone, "UTF-8");
        data += "&" + URLEncoder.encode("rom_name", "UTF-8") + "=" + URLEncoder.encode(romName, "UTF-8");
        data += "&" + URLEncoder.encode("rom_version", "UTF-8") + "=" + URLEncoder.encode(romVersion, "UTF-8");
        data += "&" + URLEncoder.encode("rom_repository", "UTF-8") + "="
                + URLEncoder.encode(romRepository, "UTF-8");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);

        URL url = new URL(link);
        url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "ROMUpdater");
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.println(data);
        out.close();

        int status = Integer.parseInt(conn.getHeaderField("ROMUpdater-status"));
        if (status == 1)
            return true;

        Log.e(TAG, "It was impossible to send data to the stastistics server ("
                + conn.getHeaderField("ROMUpdater-error") + ").");
        return false;

    } catch (Exception e) {
        Log.e(TAG, "It was impossible to send data to the stastistics server.");
        Log.e(TAG, "Error: " + e.toString());
        return false;
    }
}

From source file:au.edu.anu.portal.portlets.basiclti.support.OAuthSupport.java

/**
 * Sign a property Map with OAuth.//  www .jav  a 2s  .c  o  m
 * @param url      the url where the request is to be made
 * @param props      the map of properties to sign
 * @param method   the HTTP request method, eg POST
 * @param key      the oauth_consumer_key
 * @param secret   the shared secret
 * @return
 */
public static Map<String, String> signProperties(String url, Map<String, String> props, String method,
        String key, String secret) {

    if (key == null || secret == null) {
        log.error("Error in signProperties - key and secret must be specified");
        return null;
    }

    OAuthMessage oam = new OAuthMessage(method, url, props.entrySet());
    OAuthConsumer cons = new OAuthConsumer("about:blank", key, secret, null);
    OAuthAccessor acc = new OAuthAccessor(cons);
    try {
        oam.addRequiredParameters(acc);
        log.info("Base Message String\n" + OAuthSignatureMethod.getBaseString(oam) + "\n");

        List<Map.Entry<String, String>> params = oam.getParameters();

        Map<String, String> headers = new HashMap<String, String>();
        for (Map.Entry<String, String> p : params) {
            //as per the spec, params must be encoded
            String param = URLEncoder.encode(p.getKey(), CHARSET);
            String value = p.getValue();
            String encodedValue = value != null ? URLEncoder.encode(value, CHARSET) : "";
            headers.put(param, encodedValue);
        }
        return headers;
    } catch (OAuthException e) {
        log.error(e.getClass() + ":" + e.getMessage());
        return null;
    } catch (IOException e) {
        log.error(e.getClass() + ":" + e.getMessage());
        return null;
    } catch (URISyntaxException e) {
        log.error(e.getClass() + ":" + e.getMessage());
        return null;
    }

}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.DeliveryServicesTest.java

@Test
public void itReturnsIdOfValidDeliveryService() throws Exception {
    String encodedUrl = URLEncoder.encode("http://trafficrouter01.steering-target-1.thecdn.example.com/stuff",
            "utf-8");
    HttpGet httpGet = new HttpGet("http://localhost:3333/crs/deliveryservices?url=" + encodedUrl);

    CloseableHttpResponse response = null;
    try {/*  ww w.j a  va2 s. c o  m*/
        response = closeableHttpClient.execute(httpGet);
        String responseBody = EntityUtils.toString(response.getEntity());
        assertThat(responseBody, equalTo("{\"id\":\"steering-target-1\"}"));
    } finally {
        if (response != null)
            response.close();
    }
}

From source file:com.util.httpHistorial.java

public List<Llamadas> getHistorial(String idAccount, String page, String max, String startDate, String endDate,
        String destination) {//from   w w  w . ja  va 2s .  c om

    // String idAccount = "2";
    // String page = "1";
    // String max = "10";
    //String startDate = "2016-09-20 00:00:00";
    // String endDate = "2016-10-30 23:59:59";
    // String destination = "";
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/cdrs/history/" + idAccount + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8");
            data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8");
            data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8");
            data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8");
            data += "&" + URLEncoder.encode("destination", "UTF-8") + "="
                    + URLEncoder.encode(destination, "UTF-8");
            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString());

    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    // JSONArray dataJson = new JSONArray();
    //  dataJson = objJason.getJSONArray("data");
    String jdata = objJason.optString("data");
    String mensaje = objJason.optString("message");
    System.out.println("\n\n MENSAJE DEL SERVIDOR " + mensaje);
    //System.out.println(" el objeto jdata es "+jdata);
    objJason = new JSONObject(jdata);
    //  System.out.println("objeto normal 1 " + objJason.toString());
    //
    jdata = objJason.optString("items");
    // System.out.println("\n\n el objeto jdata es " + jdata);
    JSONArray jsonArray = new JSONArray();
    Gson gson = new Gson();
    //objJason = gson.t
    jsonArray = objJason.getJSONArray("items");
    // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString());

    List<Llamadas> llamadas = new ArrayList<Llamadas>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Llamadas llamada = new Llamadas();
        llamada.setNo(i + 1);
        llamada.setInicioLLamada(jsonArray.getJSONObject(i).getString("callstart"));
        llamada.setNumero(jsonArray.getJSONObject(i).getString("callednum"));
        llamada.setPais_operador(jsonArray.getJSONObject(i).getString("notes"));
        llamada.setDuracionSegundos(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds")));
        llamada.setCostoTotal(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost")));
        llamada.setCostoMinuto(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost")));

        long minutos = Long.parseLong(llamada.getDuracionSegundos()) / 60;
        llamada.setDuracionMinutos(minutos);

        llamadas.add(llamada);

    }

    for (int i = 0; i < llamadas.size(); i++) {
        System.out.print("\n\nNo" + llamadas.get(i).getNo());
        System.out.print("  Fecna " + llamadas.get(i).getInicioLLamada());
        System.out.print("  Numero " + llamadas.get(i).getNumero());
        System.out.print("  Pais-Operador " + llamadas.get(i).getPais_operador());
        System.out.print("  Cantidad de segundos " + llamadas.get(i).getDuracionSegundos());
        System.out.print("  Costo total " + llamadas.get(i).getCostoTotal());
        System.out.print("  costo por minuto " + llamadas.get(i).getCostoMinuto());
        System.out.print("  costo por minuto " + llamadas.get(i).getDuracionMinutos());

    }

    /**
     * List<String> list = new ArrayList<String>(); for (int i = 0; i <
     * jsonArray.length(); i++) { list.add(String.valueOf(i));
     * list.add(jsonArray.getJSONObject(i).getString("callstart"));
     * list.add(jsonArray.getJSONObject(i).getString("callednum"));
     * list.add(jsonArray.getJSONObject(i).getString("notes"));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost")));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds")));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost")));
     * } System.out.println("\n\nel array java contiene " +
     * list.toString());
     *
     */
    return llamadas;
}

From source file:azkaban.webapp.servlet.ExternalAnalyzerUtils.java

private static String buildExternalAnalyzerURL(HttpServletRequest req, String url, String pattern) {
    StringBuilder builder = new StringBuilder();
    builder.append(req.getRequestURL());
    builder.append("?");
    builder.append(req.getQueryString());
    String flowExecutionURL = builder.toString();
    String encodedFlowExecUrl = "";
    try {//www. j a  v  a  2 s  .c o m
        encodedFlowExecUrl = URLEncoder.encode(flowExecutionURL, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Specified encoding is not supported", e);
    }
    return url.replaceFirst(pattern, encodedFlowExecUrl);
}

From source file:edu.isi.wings.util.oodt.CurationServiceAPI.java

private String query(String method, String op, Object... args) {
    String url = this.curatorurl + this.service + op;
    try {/*from   w  w  w .  j  a v  a  2  s .c  o  m*/
        String params = "policy=" + URLEncoder.encode(this.policy, "UTF-8");
        for (int i = 0; i < args.length; i += 2) {
            params += "&" + args[i] + "=" + URLEncoder.encode(args[i + 1].toString(), "UTF-8");
        }

        URL urlobj = new URL(url);
        if ("GET".equals(method))
            urlobj = new URL(url + "?" + params);
        HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
        con.setRequestMethod(method);
        if (!"GET".equals(method)) {
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();
        }

        String result = IOUtils.toString(con.getInputStream());
        con.disconnect();
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.gson.oauth.Pay.java

/**
 * ??//from   ww  w  .ja  v a  2 s  .c om
 * @param params
 * @param encode
 * @return
 * @throws UnsupportedEncodingException 
 */
public static String createSign(Map<String, String> params, boolean encode)
        throws UnsupportedEncodingException {
    Set<String> keysSet = params.keySet();
    Object[] keys = keysSet.toArray();
    Arrays.sort(keys);
    StringBuffer temp = new StringBuffer();
    boolean first = true;
    for (Object key : keys) {
        if (first) {
            first = false;
        } else {
            temp.append("&");
        }
        temp.append(key).append("=");
        Object value = params.get(key);
        String valueString = "";
        if (null != value) {
            valueString = value.toString();
        }
        if (encode) {
            temp.append(URLEncoder.encode(valueString, "UTF-8"));
        } else {
            temp.append(valueString);
        }
    }
    return temp.toString();
}

From source file:org.jasig.portlet.courses.service.UPortalURLServiceImpl.java

@Override
public String getLocationUrl(Location location, PortletRequest request) {
    try {//from w  ww. ja va2  s . co m
        final String encodedLocation = URLEncoder.encode(location.getIdentifier(), "UTF-8");
        return portalContext.concat("/s/location?id=").concat(encodedLocation);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to encode location id " + location.getIdentifier());
        return null;
    }
}