1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 /***
41 * The home for utility methods that handle various encoding tasks.
42 *
43 * @author Michael Becke
44 *
45 * @since 2.0 final
46 */
47 public class EncodingUtil {
48
49 /*** Log object for this class. */
50 private static final Log LOG = LogFactory.getLog(EncodingUtil.class);
51
52 /***
53 * BitSet of www-form-url safe characters.
54 */
55 private static final BitSet WWW_FORM_URL = new BitSet(256);
56
57
58 static {
59
60 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
67 for (int i = '0'; i <= '9'; i++) {
68 WWW_FORM_URL.set(i);
69 }
70
71 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 /***
79 * Form-urlencoding routine.
80 *
81 * The default encoding for all forms is `application/x-www-form-urlencoded'.
82 * A form data set is represented in this media type as follows:
83 *
84 * The form field names and values are escaped: space characters are replaced
85 * by `+', and then reserved characters are escaped as per [URL]; that is,
86 * non-alphanumeric characters are replaced by `%HH', a percent sign and two
87 * hexadecimal digits representing the ASCII code of the character. Line breaks,
88 * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
89 *
90 * @param pairs the values to be encoded
91 * @param charset the character set of pairs to be encoded
92 *
93 * @return the urlencoded pairs
94 *
95 * @since 2.0 final
96 */
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 /***
132 * This class should not be instantiated.
133 */
134 private EncodingUtil() {
135 }
136
137 }