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.thinkgem.jeesite.modules.sso.util.Encodes.java

/**
 * URL ?, EncodeUTF-8. /*from w w w. j a v a2 s .  co m*/
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        return "";
    }
}

From source file:io.bibleget.HTTPCaller.java

/**
 *
 * @param myQuery// ww w  .  ja  v a  2s  .  co m
 * @param versions
 * @return
 */
public String sendGet(String myQuery, String versions) {
    try {
        versions = URLEncoder.encode(versions, "utf-8");
        myQuery = URLEncoder.encode(myQuery, "utf-8");
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HTTPCaller.class.getName()).log(Level.SEVERE, null, ex);
    }
    String url = "http://query.bibleget.io/index2.php?query=" + myQuery + "&version=" + versions
            + "&return=json&appid=openoffice&pluginversion=" + BibleGetIO.PLUGINVERSION;

    return getResponse(url);
}

From source file:com.dgq.utils.EncodeUtils.java

/**
 * URL ?, EncodeUTF-8./*from w  ww .java 2  s.  c o  m*/
 */
public static String urlEncode(String part) {
    try {
        return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new SecurityException("URL?!");
    }
}

From source file:com.ibasco.agql.core.AbstractWebRequest.java

protected static String encode(String element, String encoding) {
    try {/*w w w. jav a 2 s .  co m*/
        return URLEncoder.encode(element, encoding);
    } catch (UnsupportedEncodingException ignored) {
    }
    return null;
}

From source file:edu.cornell.mannlib.vitro.webapp.filestorage.FileServingHelper.java

/**
 * <p>//from  w  w w  . j  a  v  a  2s . c om
 * Combine the URI and the filename to produce a relative URL for the file
 * (relative to the context of the webapp). The filename will be URLEncoded
 * as needed.
 * </p>
 * <p>
 * This should involve stripping the default namespace from the front of the
 * URL, replacing it with the file prefix, and adding the filename to the
 * end.
 * </p>
 * 
 * @return <ul>
 *         <li>the translated URL, if the URI was in the default namespace,</li>
 *         <li>the original URI, if it wasn't in the default namespace,</li>
 *         <li>null, if the original URI or the filename was null.</li>
 *         </ul>
 */
public static String getBytestreamAliasUrl(String uri, String filename, ServletContext ctx) {
    if ((uri == null) || (filename == null)) {
        return null;
    }

    String defaultNamespace = getDefaultNamespace(ctx);

    if (!uri.startsWith(defaultNamespace)) {
        log.warn("uri does not start with the default namespace: '" + uri + "'");
        return uri;
    }
    String remainder = uri.substring(defaultNamespace.length());

    try {
        filename = URLEncoder.encode(filename, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        log.error("No UTF-8 encoding?", e); // Can't happen.
    }

    String separator = remainder.endsWith("/") ? "" : "/";
    return FILE_PATH + remainder + separator + filename;
}

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

/**
 * Obtener lista de empleados registrados.
 *
 * @return Lista de empleados consultados.
 *//*w  w w  .java  2  s .  c om*/
public ArrayList<Empleado> listarEmpleados() {

    String parametros;
    ArrayList<Empleado> lista = new ArrayList<>();

    try {
        parametros = "accion=" + URLEncoder.encode(ACCION_LISTAR, "UTF-8") + "&indice="
                + URLEncoder.encode("todo", "UTF-8");

        JSONObject respuesta = json.getRespuestaAPI(ACCESO_URL, parametros);

        if (respuesta.getInt("error") == 0) {
            JSONArray json_lista = respuesta.getJSONArray("lista");
            for (int i = 0; i < json_lista.length(); i++) {
                JSONObject o = json_lista.getJSONObject(i);
                lista.add(new Empleado("" + o.getLong("cedula"), o.getString("nombre"), o.getString("apellido"),
                        o.getString("direccion"), o.getLong("telefono") + "", o.getString("correo"),
                        o.getString("nivel"), String.valueOf(o.get("fecha_registro")), o.getString("activo"),
                        String.valueOf(o.get("fecha_activacion")),
                        String.valueOf(o.get("fecha_desactivacion"))));
            }
            new AdminDAO().agregarListaEmpleado(lista);
        } else if (respuesta.getInt("error") == 14) {
            return null;
        }
        return lista;

    } catch (Exception e) {
        Log.agregarError(e);
        System.err.println("ERROR AdministradorFunciones:107 -> " + e.toString());
        return lista;
    }
}

From source file:com.android.mail.ui.LicensesActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.licenses_activity);

    // Enable back navigation
    final ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }//from w  ww.ja  va  2  s.  com

    InputStream input = null;
    String licenseHTML = null;
    try {
        // read the raw license String from the license HTML file
        input = getResources().openRawResource(R.raw.licenses);
        final String license = IOUtils.toString(input, "UTF-8");

        // encode the license string for display as HTML in the webview
        licenseHTML = URLEncoder.encode(license, "UTF-8").replace("+", "%20");
    } catch (IOException e) {
        LogUtils.e(LogTag.getLogTag(), e, "Error reading licence file");
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException ioe) {
                // best attempt only
            }
        }
    }

    // set the license HTML into the webview
    final WebView webview = (WebView) findViewById(R.id.webview);
    webview.loadData(licenseHTML, "text/html", null);
}

From source file:com.microsoft.alm.plugin.idea.git.starters.SimpleCheckoutStarterTest.java

@Test
public void testCreateWithUriAttributesHappyEncodedUri() throws Exception {
    Map<String, String> uriMap = new HashMap<String, String>() {
        {//from  ww w  .j  a va 2  s .c om
            put("url", URLEncoder.encode(VALID_GIT_URL, "UTF8"));
            put("EncFormat", "UTF8");
        }
    };

    SimpleCheckoutStarter starter = SimpleCheckoutStarter.createWithUriAttributes(uriMap);
    Assert.assertEquals(VALID_GIT_URL, starter.getGitUrl());
}

From source file:com.mboarder.util.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./* w w  w  . j  a  v a 2s. 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(TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TAG, "getInputStream()");
            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:documentToVector.spotlight.evaluation.external.DBpediaSpotlightClient.java

@Override
public List<DBpediaResource> extract(Text text) throws AnnotationException {

    LOG.info("Querying API.");
    String spotlightResponse;//from  w ww .j  av a2  s  .  c  om
    try {
        GetMethod getMethod = new GetMethod(API_URL + "rest/annotate/?" + "confidence=" + CONFIDENCE
                + "&support=" + SUPPORT + "&text=" + URLEncoder.encode(text.text(), "utf-8"));
        getMethod.addRequestHeader(new Header("Accept", "application/json"));

        spotlightResponse = request(getMethod);
    } catch (UnsupportedEncodingException e) {
        throw new AnnotationException("Could not encode text.", e);
    }

    assert spotlightResponse != null;

    JSONObject resultJSON = null;
    JSONArray entities = null;

    try {
        resultJSON = new JSONObject(spotlightResponse);
        entities = resultJSON.getJSONArray("Resources");
    } catch (JSONException e) {
        throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
    }

    LinkedList<DBpediaResource> resources = new LinkedList<DBpediaResource>();
    for (int i = 0; i < entities.length(); i++) {
        try {
            JSONObject entity = entities.getJSONObject(i);
            resources.add(new DBpediaResource(entity.getString("@URI"),
                    Integer.parseInt(entity.getString("@support")))

            );

        } catch (JSONException e) {
            LOG.error("JSON exception " + e);
        }

    }

    return resources;
}