We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Encoding for URL
Page Index Toggle Pages: 1
Encoding for URL (Read 510 times)
Encoding for URL
Oct 3rd, 2006, 12:29am
 
Just thought I would share this little bit with anyone who might run into a use for it.

I've got a UTF-8 string I'm going to put into a URL with characters that are not ASCII. Java's own URLEncoder class interprets Strings as ASCII and will mess up my UTF-8. This code runs through byte by byte to catch those UTF chars that are more than just 1 byte long!

Correctly converts things like "Sigur Rós" into "Sigur+R%C3%B3s"

Any suggestions for improvement would be appreciated!

Quote:
String URLEncode(String string){
 String output = new String();
 try{
   byte[] input = string.getBytes("UTF-8");
   for(int i=0; i<input.length; i++){
     if(input[i]<0)
       output += '%' + hex(input[i]);
     else if(input[i]==32)
       output += '+';
     else
       output += char(input[i]);
   }
 }
 catch(UnsupportedEncodingException e){
   e.printStackTrace();
 }

 return output;
}
Page Index Toggle Pages: 1