Cómo hacer la decodificación de URL en Java?


En Java, quiero convertir esto:

https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type

A esto:

https://mywebsite/docs/english/site/mybook.do&request_type

Esto es lo que tengo hasta ahora:

class StringUTF 
{
    public static void main(String[] args) 
    {
        try{
            String url = 
               "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do" +
               "%3Frequest_type%3D%26type%3Dprivate";

            System.out.println(url+"Hello World!------->" +
                new String(url.getBytes("UTF-8"),"ASCII"));
        }
        catch(Exception E){
        }
    }
}

Pero no funciona bien. ¿Cómo se llaman estos formatos %3A y %2F y cómo los convierto?

Author: Eric Leschinski, 2011-05-26

9 answers

Esto no tiene nada que ver con codificaciones de caracteres como UTF-8 o ASCII. La cadena que tiene allí es URL codificada. Este tipo de codificación es algo completamente diferente a la codificación de caracteres.

Intenta algo como esto:

String result = java.net.URLDecoder.decode(url, "UTF-8");

Tenga en cuenta que una codificación de caracteres (como UTF-8 o ASCII) es lo que determina la asignación de caracteres a bytes sin procesar. Para una buena introducción a las codificaciones de caracteres, vea este artículo.

 531
Author: Jesper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-29 15:21:02

La cadena que tienes está codificada en application/x-www-form-urlencoded.

Use URLDecoder para convertirlo a cadena Java.

URLDecoder.decode( url, "UTF-8" );
 44
Author: Alexander Pogrebnyak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-26 12:02:41

Esto ha sido respondido antes (¡aunque esta pregunta fue la primera!):

"Debe usar java.net.URI para hacer esto, ya que la clase URLDecoder hace la decodificación x-www-form-urlencoded que es incorrecta (a pesar del nombre, es para datos de formulario)."

Básicamente:

String url = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type";
System.out.println(new java.net.URI(url).getPath());

Te dará:

https://mywebsite/docs/english/site/mybook.do?request_type
 37
Author: Nick Grealy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:32

%3A y %2F son caracteres codificados en URL. Utilice este código java para convertirlos de nuevo en : y /

String decoded = java.net.URLDecoder.decode(url, "UTF-8");
 13
Author: laz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-09 00:33:53
 try {
        String result = URLDecoder.decode(urlString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 5
Author: Hsm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-14 17:44:50

Utilizo apache commons

String decodedUrl = new URLCodec().decode(url);

El conjunto de caracteres predeterminado es UTF-8

 3
Author: Sorter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-10 12:31:02
public String decodeString(String URL)
    {

    String urlString="";
    try {
        urlString = URLDecoder.decode(URL,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block

        }

        return urlString;

    }
 3
Author: Ronak Poriya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 07:12:51
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

public class URLDecoding { 

    String decoded = "";

    public String decodeMethod(String url) throws UnsupportedEncodingException
    {
        decoded = java.net.URLDecoder.decode(url, "UTF-8"); 
        return  decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
    }

    public String getPathMethod(String url) throws URISyntaxException 
    {
        decoded = new java.net.URI(url).getPath();  
        return  decoded; 
    }

    public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException 
    {
        System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type")); 
        System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest")); 

    } 

}

Puedes seleccionar tu método sabiamente:)

 1
Author: rinuthomaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-15 04:29:28

Solo usar URLDecoder.decode una vez no será suficiente .

Por ejemplo:

Debido a que la misma URL se puede codificar varias veces, necesitamos decodificarla hasta que la URL no pueda decodificarse más. Por ejemplo, "video % 252Fmp4" es el resultado de dos codificaciones. Al decodificarlo una vez, obtenemos "video%2Fmp4". Ahora la URL necesita ser decodificada aún más para que obtengamos "video / mp4", que es el resultado.

Aquí está el código que funciona para todos estos casos:

public static String decode(String url)  
      {  
                try {  
                     String prevURL="";  
                     String decodeURL=url;  
                     while(!prevURL.equals(decodeURL))  
                     {  
                          prevURL=decodeURL;  
                          decodeURL=URLDecoder.decode( decodeURL, "UTF-8" );  
                     }  
                     return decodeURL;  
                } catch (UnsupportedEncodingException e) {  
                     return "Issue while decoding" +e.getMessage();  
                }  
      }
 0
Author: Natesh bhat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-08 17:22:09