DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Hear from the experts in our "DZone 2023 Preview: DevOps Edition" on Fri, Jan 27!
Save your seat
  1. DZone
  2. Coding
  3. Java
  4. URL Encoding and Decoding Using Java

URL Encoding and Decoding Using Java

If you find yourself encoding and decoding URLs often, take a look at how to do it in Java while staying on alert in case you need multiple iterations.

Anurag Jain user avatar by
Anurag Jain
·
Mar. 24, 17 · Tutorial
Like (19)
Save
Tweet
Share
207.78K Views

Join the DZone community and get the full member experience.

Join For Free

It is a common requirement to implement URL encoding and decoding in Java while creating crawlers or downloaders. This post focuses on creating modules for encoding and decoding of a passed URL. You can take a look at the source code on GitHub.

Main Method

 public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String url="https%3A%2F%2Fr1---sn-ci5gup-cags.googlevideo.com%2Fvideoplayback%3Fpcm2cms%3Dyes%26mime%3Dvideo%252Fmp4%26pl%3D21%26itag%3D22%26\u0026itag=43\u0026type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22\u0026quality=medium";  
           String url2="https://r1---sn-ci5gup-cags.googlevideo.com/videoplayback?pcm2cms=yes&mime=video/mp4&pl=21&itag=22&&itag=43&type=video/webm; codecs=\"vp8.0, vorbis\"&quality=medium";  
           String decodeURL = decode(url);  
           System.out.println("Decoded URL: "+decodeURL);  
           String encodeURL = encode(url2);  
           System.out.println("Encoded URL2: "+encodeURL);  
      }  


How It Works

  1. url is the variable containing the encoded URL that we want to decode.

  2. url2 is the variable containing the URL we want to encode.

  3. We call the decode method, which decodes and prints the URL.

  4. We call the encode method, which encodes and prints url2.

Encode Method

      public static String encode(String url)  
      {  
                try {  
                     String encodeURL=URLEncoder.encode( url, "UTF-8" );  
                     return encodeURL;  
                } catch (UnsupportedEncodingException e) {  
                     return "Issue while encoding" +e.getMessage();  
                }  
      }  


How It Works

  1. We use the encode method of a predefined Java class named URLEncoder.

  2. The encode method of URLEncoder takes two arguments:

    1. The first argument defines the URL to be encoded.

    2. The second argument defines the encoding scheme to be used.

  3. After encoding, the resulting encoded URL is returned.

Decode Method

      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();  
                }  
      }  


How It Works

  1. Because the same URL can be encoded multiple times, we need to decode it until the URL cannnot be decoded further. For example, "video%252Fmp4" is the result of two encodings. Upon decoding it once, we get "video%2Fmp4". Now the URL needs to be further decoded so that we get "video/mp4", which is the result.

  2. We use the decode method of a predefined Java class named URLDecoder.

  3. The decode method of URLDecoder takes two arguments:

    1. The first argument defines the URL to be decoded.

    2. The second argument defines the decoding scheme to be used.

  4. After decoding, the resulting decoded URL is returned.

  5. We create two variables: prevURL, which is empty, and decodeURL, which contains the URL to be decoded.

     Variable State:  
     prevURL = ""  
     decodeURL ="somethingvideo%252Fmp4"  
    

  6. We create an iteration that runs until prevURL!=decodeURL

  7. Now we update prevURL to decodeURL and update decodeURL with the decoded value of the URL passed.

     Variable State:  
     prevURL = "somethingvideo%252Fmp4"  
     decodeURL ="somethingvideo%2Fmp4"  
    

  8. As you can see, prevURL!=decodeURL, so we run it again.

     Variable State:  
     prevURL = "somethingvideo%2Fmp4"  
     decodeURL ="somethingvideo/mp4"  
    

  9. And again.

     Variable State:  
     prevURL = "somethingvideo/mp4"  
     decodeURL ="somethingvideo/mp4"  
    

  10. Now, prevURL=decodeURL, so the decoded URL is returned.

Output

 Decoded URL: https://r1---sn-ci5gup-cags.googlevideo.com/videoplayback?pcm2cms=yes&mime=video/mp4&pl=21&itag=22&&itag=43&type=video/webm; codecs="vp8.0, vorbis"&quality=medium  
 Encoded URL2: https%3A%2F%2Fr1---sn-ci5gup-cags.googlevideo.com%2Fvideoplayback%3Fpcm2cms%3Dyes%26mime%3Dvideo%2Fmp4%26pl%3D21%26itag%3D22%26%26itag%3D43%26type%3Dvideo%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22%26quality%3Dmedium  


Full Program

 package com.cooltrickshome;  
 import java.io.UnsupportedEncodingException;  
 import java.net.URLDecoder;  
 import java.net.URLEncoder;  
 public class URLEncodeDecode {  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String url="https%3A%2F%2Fr1---sn-ci5gup-cags.googlevideo.com%2Fvideoplayback%3Fpcm2cms%3Dyes%26mime%3Dvideo%252Fmp4%26pl%3D21%26itag%3D22%26\u0026itag=43\u0026type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22\u0026quality=medium";  
           String url2="https://r1---sn-ci5gup-cags.googlevideo.com/videoplayback?pcm2cms=yes&mime=video/mp4&pl=21&itag=22&&itag=43&type=video/webm; codecs=\"vp8.0, vorbis\"&quality=medium";  
           String decodeURL = decode(url);  
           System.out.println("Decoded URL: "+decodeURL);  
           String encodeURL = encode(url2);  
           System.out.println("Encoded URL2: "+encodeURL);  
      }  
      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();  
                }  
      }  
      public static String encode(String url)  
      {  
                try {  
                     String encodeURL=URLEncoder.encode( url, "UTF-8" );  
                     return encodeURL;  
                } catch (UnsupportedEncodingException e) {  
                     return "Issue while encoding" +e.getMessage();  
                }  
      }  
 }  


I hope this helps!

Java (programming language)

Published at DZone with permission of Anurag Jain, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Simulate Network Latency and Packet Drop In Linux
  • A Beginner's Guide to Back-End Development
  • Core Machine Learning Metrics
  • How To Convert HTML to PNG in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: