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:es.warp.killthedj.spotify.SpotifyQuery.java

public ArrayList<AvailableTrack> get(String query)
        throws SpotifyQueryNetworkException, SpotifyJSONParseException, UnsupportedEncodingException {
    return ParseJSONResponse(spotifyHTTPGet.get(URLEncoder.encode(query, "UTF-8")));
}

From source file:com.cmsoftware.keyron.controlador.AplicacionFunciones.java

/**
 * Chequea si hay una versin mas reciente de la aplicacin.
 *
 * @return Cdigo de respuesta del web service.
 *//*from  ww w.  j a  v  a 2  s  .  com*/
public int chequearVersion() {
    String parametros;

    try {
        parametros = "accion=" + URLEncoder.encode(ACCION_CHEQUEAR, "UTF-8") + "&version="
                + URLEncoder.encode(Configuracion.getInstancia().getVersion() + "", "UTF-8") + "&plataforma="
                + URLEncoder.encode("windows", "UTF-8");
        JSONObject respuesta = json.getRespuestaAPI(ACCESO_URL_APLICACION, parametros);
        int key_error = respuesta.getInt("error");

        if (key_error == 0) {
            JSONObject update = respuesta.getJSONObject("actualizacion");
            Actualizacion actualizacion = new Actualizacion();
            actualizacion.setVersion(update.getInt("version"));
            actualizacion.setPlataforma(update.getString("plataforma"));
            actualizacion.setFecha(update.getString("fecha"));
            actualizacion.setLink(update.getString("enlace"));
            actualizacion.setDescripcion(update.getString("descripcion"));
            actualizacion.setTamano(update.getLong("tamano"));
            Optimizacion.getInstancia().setActualizacion(actualizacion);
        }
        return key_error;
    } catch (Exception e) {
        System.err.println("ERROR AplicacionFunciones:79 -> " + e.toString());
        Log.agregarError(e);
        return -1;
    }
}

From source file:net.task.ParserTask.java

@Scheduled(fixedRate = 1000 * 60 * 60 * 24)
public void getJobsTask() {

    List<Job> allJobs = new ArrayList<Job>();
    boolean isLastPage = false;
    int pageCount = 1;

    // goes through pages and collects job and employer ids and links   
    while (!isLastPage) {

        String urlParameters = null;

        try {/*from  ww  w . j  ava 2  s .  c  om*/
            urlParameters = "?published=" + URLEncoder.encode("2", "UTF-8") + "&page="
                    + URLEncoder.encode(String.valueOf(pageCount), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException: " + e.toString() + ". Parameters: " + urlParameters);
            e.printStackTrace();
        }

        // svi poslovi
        String response = null;
        try {
            response = HttpRequestHandling.sendGet("http://www.moj-posao.net/Pretraga-Poslova/", urlParameters);
        } catch (IOException e) {
            log.error("IOException: " + e.toString() + ". Parameters: " + urlParameters);
            e.printStackTrace();
        }

        jp.setHtml(response);
        if (jp.featuredJobsExist()) {
            allJobs = jp.getFeaturedJobIdAndLink(allJobs);
        }

        isLastPage = jp.checkIfLastPage();
        if (isLastPage) {
            if (jp.regionalJobFirst()) {
                break;
            } else {
                allJobs = jp.getJobIdAndLink(allJobs);
            }
        } else {
            allJobs = jp.getJobIdAndLink(allJobs);
        }

        pageCount++;
    }

    String response = null;

    // iterates through jobs and saves them into database if they don't exist
    int count = 0;
    for (Job job : allJobs) {

        // if job doesn't exist in database
        if (jobDaoManager.getJobById(job.getId()) == null) {

            Employer employer = null;

            // if employer id is undefined on page
            if (job.getEmployer().getId() == 0 || job.getEmployer().getId() >= 10000000) {
                employer = employerDaoManager.getEmployerByName(job.getEmployer().getName());

                // if employer exists in database
                if (employer != null) {
                    job.setEmployer(employer);
                } else {
                    // employer doesn't exist in database
                    do {
                        int employerId = Utils.generateRandomNumber(10000000, 99999999);
                        employer = employerDaoManager.getEmployerById(employerId);
                        if (employer == null) {
                            job.getEmployer().setId(employerId);
                            employerDaoManager.saveEmployer(job.getEmployer());
                            break;
                        }
                    } while (employer != null);
                }
            } else {

                employer = employerDaoManager.getEmployerById(job.getEmployer().getId());

                // if employer exists in database
                if (employer != null) {
                    job.setEmployer(employer);
                } else {
                    try {
                        response = HttpRequestHandling.sendGet(job.getEmployer().getLink(), "");
                    } catch (IOException e) {
                        log.error("IOException: " + e.toString() + ". Employer link: "
                                + job.getEmployer().getLink());
                        e.printStackTrace();
                    }

                    jp.setHtml(response);
                    String address = jp.getEmployerAddress();
                    job.getEmployer().setAddress(address);

                    employerDaoManager.saveEmployer(job.getEmployer());
                }
            }

            try {
                response = HttpRequestHandling.sendGet(job.getLink(), "");
            } catch (IOException e) {
                log.error("IOException: " + e.toString() + ". Job link: " + job.getLink());
                e.printStackTrace();
            }

            jp.setHtml(response);

            String title = jp.getTitle();
            if (title == null || title.equals("")) {
                log.error("Title error = no title, job_id: " + job.getId());
                continue;
            }

            Date deadline = jp.getApplicationDeadline();
            if (deadline == null) {
                log.error("Deadline error = no deadline, job_id: " + job.getId());
                continue;
            }

            job.setTitle(title);
            job.setDeadline(jp.getApplicationDeadline());
            job.setDescription(jp.getDescription());
            job.setConditions(jp.getConditions());
            job.setQualifications(jp.getQualification());
            job.setYearsOfExperience(jp.getYearsOfExperience());
            job.setLanguages(jp.getLanguages());
            job.setSkills(jp.getSkills());
            job.setDrivingLicence(jp.getDrivingLicense());
            job.setEmployerOffer(jp.getEmployeeOffer());
            job.setJobTypes(jp.getJobTypes());
            job.setCategories(jp.getCategories());
            job.setCounties(jp.getCounties());

            // traenje tehnologija - ovo se radi samo u slu?aju da je kategorija posla = IT
            if (job.getCategories() != null) {
                Iterator<Category> itr = job.getCategories().iterator();
                while (itr.hasNext()) {
                    Category cat = itr.next();
                    if (cat.getId() == 11) {
                        job.setTechSkills(jp.getTechSkills());
                    }
                }
            }

            jobDaoManager.saveJob(job);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("InterruptedException: " + e.toString());
                e.printStackTrace();
            }
            count++;
        }
    }
    System.out.println();
    System.out.println("Gotovo!");
}

From source file:com.att.nsa.mr.client.impl.MRConstants.java

public static String escape(String s) {
    try {// w  w  w  . jav  a 2s  .co  m
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.jtiger.modules.ecside.util.ECSideUtils.java

public static String encodeFileName(String fileName, String agent) throws UnsupportedEncodingException {
    String codedfilename = null;//  w  w w .j a v a 2s .  c  o m
    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;
        //         }
    } 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:net.sourceforge.vulcan.web.JstlFunctions.java

public static String encode(String s) {
    try {//from  w w w.  j ava2 s .  c o m
        // replace + with %20 because + is only appropriate for query strings, not for paths.
        return URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Send an HTTP(s) request with POST parameters.
 * /*from   ww w  . ja v a2 s.  c om*/
 * @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());
    Loger.d(LOG_TAG, "Posting crash report data");
    wr.write(dataBfr.toString());
    wr.flush();
    wr.close();

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

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

From source file:it.av.fac.driver.APIClient.java

public String queryRequest(String userToken, String resource) {
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(endpoint + QUERY_PATH);

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("request", URLEncoder.encode(resource, "UTF-8")));
        nvps.add(new BasicNameValuePair("token", URLEncoder.encode(userToken, "UTF-8")));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        // Create a custom response handler
        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }/*from  w  w  w  . ja v  a 2  s  .  c  om*/
        };

        return httpclient.execute(httpPost, responseHandler);
    } catch (IOException ex) {
        Logger.getLogger(APIClient.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.javielinux.utils.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./* www.  j a va2 s.co  m*/
 * @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(Utils.TAG, "Conectadndo a " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            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.example.wrappers.PlaceWrapper.java

/**
 * concatURLValues format a param's arguments correctly.
 * Only used for params that accept multiple values.
 * @param values the array of strings which represent all the values which should be included in the request.
 * @returns A string which has proper URL encoding of the list of values.
 *///from w ww. j a  v a 2  s.co m
public static String concatURLValues(String... values) {
    if (values.length == 0)
        return "";

    StringBuilder sb = new StringBuilder("");
    for (String v : values) {
        sb.append(v);
        if (v != "")
            sb.append('|');
    }
    if (sb.length() > 0)
        sb.deleteCharAt(sb.length() - 1);

    try {
        return URLEncoder.encode(sb.toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("UTF-8 encoding not supported");
    }
}