Quantcast
Viewing all articles
Browse latest Browse all 1037

Java: How to Encode or Decode URL String Or Form Parameter

Image may be NSFW.
Clik here to view.
Java Tutorial Encoding Decoding Crunchify Tips Java: How to Encode or Decode URL String Or Form Parameter

In Java Examples, when using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands.

Usually, parameters are accessed from a request in an already decoded format (via request.getParameter()), so no decoding is necessary. However, occasionally certain situations arise where you need to decode a string that has been URL encoded (for instance, by the URLEncoder.encode() method or the javascript escape() function).

package com.crunchify.tutorials;

import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyEncodeDecodeExample {

	public static void main(String[] args) throws Exception {

		String crunchifyValue1 = "This is a simple Example from Crunchify";
		String ecodedValue1 = URLEncoder.encode(crunchifyValue1, "UTF-8");
		String decodedValue1 = URLDecoder.decode(ecodedValue1, "UTF-8");
		System.out.println("crunchifyValue1 after encoding => " + ecodedValue1);
		System.out.println("crunchifyValue1 after decoding (Original Value): => " + decodedValue1);

		String crunchifyValue2 = "Hello There, We started accepting Guest-Posts on Crunchify...";
		String encodedValue2 = URLEncoder.encode(crunchifyValue2, "UTF-8");
		String decodedValue2 = URLDecoder.decode(encodedValue2, "UTF-8");
		System.out.println("\ncrunchifyValue2 after encoding => " + encodedValue2);
		System.out.println("crunchifyValue2 after decoding (Original Value) => " + decodedValue2);

	}
}

Other must read:

Output:

crunchifyValue1 after encoding => This+is+a+simple+Example+from+Crunchify
crunchifyValue1 after decoding (Original Value): => This is a simple Example from Crunchify

crunchifyValue2 after encoding => Hello+There%2C+We+started+accepting+Guest-Posts+on+Crunchify...
crunchifyValue2 after decoding (Original Value) => Hello There, We started accepting Guest-Posts on Crunchify...

URL encoding is required much more often than URL decoding, since decoding usually takes place automatically during calls the request.getParameter(). However, it is good to know that URLDecoder.decode() exists for the occasional situation where it is needed.

Image may be NSFW.
Clik here to view.
URL Encode Decode Example Crunchify Tutorials Java: How to Encode or Decode URL String Or Form Parameter

The post Java: How to Encode or Decode URL String Or Form Parameter appeared first on Crunchify.

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 1037

Trending Articles