Here you will learn how to encode or decode url parameters in java.
When we submit a form by using GET method then the parameters are automatically encoded and appended to the url. In situation when we have to send data using url without submitting form then we have to append the parameters to url. The url may look like this.
http://www.example.com/demo?parameter=value
In this case the parameter value contains special characters like space, comma, etc. So we have to encode the value before appending it to the url. This can be done easily in java usingĀ URLEncoder.encode() method. Its first argument is the parameter to encode and second argument is the encoding scheme.
Below I have shown how to use this method.
How to Encode or Decode URL Parameters in Java
package com; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class EncodeDecodeParameters { public static void main(String...s){ String parameter = "Samsung S7, iPhone 7"; String encodedParameter, decodedParameter; //encoding and decoding url parameters try { encodedParameter = URLEncoder.encode(parameter, "UTF-8"); decodedParameter = URLDecoder.decode(encodedParameter, "UTF-8"); System.out.println("Encoded Parameter:" + encodedParameter); System.out.println("Decoded Parameter:" + decodedParameter); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
Output
Encoded Parameter:Samsung+S7%2C+iPhone+7
Decoded Parameter:Samsung S7, iPhone 7
You can see that space is converted to + and comma is converted to %2C. In this way we encode or decode url parameters in java.
I want to learn programming