1 31 package org.apache.commons.httpclient.util; 32 33 import java.util.BitSet ; 34 35 import org.apache.commons.httpclient.NameValuePair; 36 import org.apache.commons.httpclient.URIException; 37 import org.apache.commons.logging.Log; 38 import org.apache.commons.logging.LogFactory; 39 40 47 public class EncodingUtil { 48 49 50 private static final Log LOG = LogFactory.getLog(EncodingUtil.class); 51 52 55 private static final BitSet WWW_FORM_URL = new BitSet (256); 56 57 static { 59 for (int i = 'a'; i <= 'z'; i++) { 61 WWW_FORM_URL.set(i); 62 } 63 for (int i = 'A'; i <= 'Z'; i++) { 64 WWW_FORM_URL.set(i); 65 } 66 for (int i = '0'; i <= '9'; i++) { 68 WWW_FORM_URL.set(i); 69 } 70 WWW_FORM_URL.set(' '); 72 WWW_FORM_URL.set('-'); 73 WWW_FORM_URL.set('_'); 74 WWW_FORM_URL.set('.'); 75 WWW_FORM_URL.set('*'); 76 } 77 78 97 public static String formUrlEncode(NameValuePair[] pairs, String charset) { 98 99 StringBuffer buf = new StringBuffer (); 100 for (int i = 0; i < pairs.length; i++) { 101 if (pairs[i].getName() != null) { 102 if (i > 0) { 103 buf.append("&"); 104 } 105 String queryName = pairs[i].getName(); 106 try { 107 queryName = URIUtil.encode(queryName, WWW_FORM_URL, charset).replace(' ', '+'); 108 } catch (URIException urie) { 109 LOG.error("Error encoding pair name: " + queryName, urie); 110 } 111 buf.append(queryName); 112 buf.append("="); 113 if (pairs[i].getValue() != null) { 114 String queryValue = pairs[i].getValue(); 115 try { 116 queryValue = URIUtil.encode( 117 queryValue, 118 WWW_FORM_URL, 119 charset 120 ).replace(' ', '+'); 121 } catch (URIException urie) { 122 LOG.error("Error encoding pair value: " + queryValue, urie); 123 } 124 buf.append(queryValue); 125 } 126 } 127 } 128 return buf.toString(); 129 } 130 131 134 private EncodingUtil() { 135 } 136 137 } 138 | Popular Tags |