I wrote this code for encoding a string into URL
Code:
package URLencode;
import java.util.Scanner;
public class URLencode {
private static final String notEnc =
"abcdefghijklmnopqrsuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789.*_-";
private static final char[] hexChar = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F'
};
public static void main (String args[])
{
Scanner keyboardScanner = new Scanner (System.in);
System.out.println("Enter a line of text to be URL encoded...");
String text = keyboardScanner.nextLine();
System.out.println("The URL entered is: " + text);
System.out.println("The length of chars of URL entered is: " + text.length());
StringBuilder result = new StringBuilder(text.length());
for (int n = 0; n < text.length(); ++n) {
char c = text.charAt(n);
System.out.println("The encoded URL is: " + text);
System.out.println("The length of chars is: " + text.length());
if (notEnc.indexOf(c) != -1) {
StringBuilder append = result.append(c);
}
else if (c == ' ') {
result.append('+');
}
else
{
String hexValue = Integer.toHexString(c);
StringBuilder append = result.append('%');
result.append(hexChar[(c >> 4) & 0xF]);
result.append(hexChar[c & 0xF]);
}
}
}
}
but it does not substitute '+' for the blanks and it loops many times.??
here are 2 sample outputs but I cannot get it to do that
Enter a line of text to be URL encoded
This should have plus symbols for blanks
The string read is: This should have plus symbols for blanks
Length in chars is: 40
The encoded string: This+should+have+plus+symbols+for+blanks
Length in chars is: 40
Enter a line of text to be URL encoded
This should have hex 2f for /
The string read is: This should have hex 2f for /
Length in chars is: 29
The encoded string: This+should+have+hex+2f+for+%2f
Length in chars is: 31