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:javaphpmysql.JavaPHPMySQL.java

public static void sendPost() {
    //Creamos un objeto JSON
    JSONObject jsonObj = new JSONObject();
    //Aadimos el nombre, apellidos y email del usuario
    jsonObj.put("nombre", nombre);
    jsonObj.put("apellidos", apellidos);
    jsonObj.put("email", email);
    //Creamos una lista para almacenar el JSON
    List l = new LinkedList();
    l.addAll(Arrays.asList(jsonObj));
    //Generamos el String JSON
    String jsonString = JSONValue.toJSONString(l);
    System.out.println("JSON GENERADO:");
    System.out.println(jsonString);
    System.out.println("");

    try {//from www  .  j a va2 s.  c  o m
        //Codificar el json a URL
        jsonString = URLEncoder.encode(jsonString, "UTF-8");
        //Generar la URL
        String url = SERVER_PATH + "listenPost.php";
        //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON
        URL obj = new URL(url);
        //Creamos un objeto de conexin
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //Aadimos la cabecera
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //Creamos los parametros para enviar
        String urlParameters = "json=" + jsonString;
        // Enviamos los datos por POST
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
        //Capturamos la respuesta del servidor
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        //Mostramos la respuesta del servidor por consola
        System.out.println(response);
        //cerramos la conexin
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:jp.mixi.android.sdk.util.UrlUtils.java

/**
 * map???//from   w ww.  j a v  a 2  s .  c o m
 * 
 * @param params ?Map
 * @return ???String
 */
public static String encodeUrl(Map<String, String> params) {

    if (params == null || params.isEmpty()) {
        return "";
    }
    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for (String key : params.keySet()) {
        if (first) {
            first = false;
        } else {
            builder.append(PARAM_SEPARATOR);
        }
        String value = params.get(key);
        if (key != null && value != null) {

            try {
                builder.append(URLEncoder.encode(key, HTTP.UTF_8) + EQUAL
                        + URLEncoder.encode(params.get(key), HTTP.UTF_8));
            } catch (UnsupportedEncodingException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }
        }
    }
    return builder.toString();
}

From source file:se.vgregion.util.HTTPUtils.java

public static String encode(String value) {
    try {// w ww  . jav a 2 s.c  om
        return URLEncoder.encode(value, "utf-8");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.miyue.util.EncoderUtil.java

/**
 * URL ?, EncodeUTF-8. //from  w ww.  jav  a 2 s  .  co  m
 */
public static String URLEncode(String input) {
    try {
        return URLEncoder.encode(input, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unsupported Encoding Exception", e);
    }
}

From source file:com.surfs.storage.common.util.HttpUtils.java

public static String getUrlForParams(String ip, String port, String servicePath, String serviceName,
        Map<String, String> args) throws UnsupportedEncodingException {
    StringBuilder params = new StringBuilder();
    params.append("http://");
    params.append(ip);/*from w w w .  j av  a 2  s.  c  o m*/
    params.append(":");
    params.append(port);
    params.append(servicePath);
    params.append(serviceName);
    params.append("?");

    int size = args.size();
    // args
    for (Entry<String, String> arg : args.entrySet()) {
        --size;
        params.append(arg.getKey() + "=");
        params.append(URLEncoder.encode(arg.getValue(), "UTF-8"));
        if (size != 0)
            params.append("&");
    }

    return params.toString();
}

From source file:com.fastbootmobile.encore.api.freebase.FreeBaseClient.java

/**
 * Fetches an Artist Image URL/*from  ww  w.  j  av a 2s.c o  m*/
 * @param artist The name of the artist
 * @return An URL to an image representing this artist
 * @throws JSONException
 * @throws RateLimitException
 * @throws IOException
 */
public static String getArtistImageUrl(String artist) throws JSONException, RateLimitException, IOException {
    if (artist == null) {
        Log.e(TAG, "getArtistImageUrl: Null artist requested");
        return null;
    }

    final String ecFilter = URLEncoder.encode("(all type:/music/artist)", "UTF-8");
    final String ecArtist = URLEncoder.encode(artist, "UTF-8");

    JSONObject object = JsonGet.getObject(API_ENDPOINT,
            "query=" + ecArtist + "&filter=" + ecFilter + "&limit=1", true);

    JSONArray result = object.getJSONArray("result");
    if (result.length() > 0) {
        JSONObject firstItem = result.getJSONObject(0);
        String metaId = firstItem.getString("mid");

        // While we could get an image immediately, we're not sure there's actually an image
        // for that topic. We do one more query to not end up with an ugly "NO IMAGE" result.
        // We do take the risk however by allowing the image anyway if we go above the rate limit
        // of Google's API, as the topic endpoint is rate-limited and we're not using any API key.
        object = JsonGet.getObject(TOPIC_ENDPOINT + metaId, "filter=/common/topic/image&limit=1", true);

        if (object.has("property") || object.has("error")) {
            return IMAGE_ENDPOINT + metaId + "?maxwidth=800&maxheight=800";
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.intellij.tasks.impl.BaseRepositoryImpl.java

protected static String encodeUrl(@Nonnull String s) {
    try {/* ww w. j a va  2  s .  co  m*/
        return URLEncoder.encode(s, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.knowledgebooks.rdf.SparqlClient.java

public SparqlClient(String endpoint_URL, String sparql) throws Exception {
    //System.out.println("SparqlClient("+endpoint_URL+", "+sparql+")");
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);

    String req = URLEncoder.encode(sparql, "utf-8");
    HttpMethod method = new GetMethod(endpoint_URL + "?query=" + req);
    method.setFollowRedirects(false);/*w ww . j  av  a 2s  . c o  m*/
    try {
        client.executeMethod(method);
        //System.out.println(method.getResponseBodyAsString());
        //if (true) return;
        InputStream ins = method.getResponseBodyAsStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser sax = factory.newSAXParser();
        sax.parse(ins, this);
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + endpoint_URL + "'");
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + endpoint_URL + "'");
    }
    method.releaseConnection();
}

From source file:io.wcm.sling.commons.util.EscapeTest.java

@Test
public void testUrlEncode() throws UnsupportedEncodingException {
    assertEquals(URLEncoder.encode("abc", CharEncoding.UTF_8), Escape.urlEncode("abc"));
    assertEquals(URLEncoder.encode("Abc_", CharEncoding.UTF_8),
            Escape.urlEncode("Abc_"));
    assertEquals(URLEncoder.encode("Der Jodelkaiser", CharEncoding.UTF_8), Escape.urlEncode("Der Jodelkaiser"));
    assertEquals(URLEncoder.encode("Der  Jodelkaiser", CharEncoding.UTF_8),
            Escape.urlEncode("Der  Jodelkaiser"));
    assertEquals(URLEncoder.encode("lsa$5x !?_", CharEncoding.UTF_8),
            Escape.urlEncode("lsa$5x !?_"));
}

From source file:org.obiba.mica.file.FileUtils.java

/**
 * Encode file path to be Shiro-safe.//from w w  w.  j av  a2s  .  c o m
 *
 * @param path
 * @return
 */
public static String encode(String path) {
    if (path == null)
        return null;
    try {
        return URLEncoder.encode(path, "UTF-8").replaceAll("%2F", "/");
    } catch (UnsupportedEncodingException e) {
        return path;
    }
}