1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.http;
17
18 import java.io.UnsupportedEncodingException;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.net.URLEncoder;
22 import java.nio.charset.Charset;
23 import java.nio.charset.UnsupportedCharsetException;
24 import java.util.ArrayList;
25 import java.util.List;
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class QueryStringEncoder {
42
43 private final Charset charset;
44 private final String uri;
45 private final List<Param> params = new ArrayList<Param>();
46
47
48
49
50
51 public QueryStringEncoder(String uri) {
52 this(uri, HttpConstants.DEFAULT_CHARSET);
53 }
54
55
56
57
58
59 public QueryStringEncoder(String uri, Charset charset) {
60 if (uri == null) {
61 throw new NullPointerException("uri");
62 }
63 if (charset == null) {
64 throw new NullPointerException("charset");
65 }
66
67 this.uri = uri;
68 this.charset = charset;
69 }
70
71
72
73
74 @Deprecated
75 public QueryStringEncoder(String uri, String charset) {
76 this(uri, Charset.forName(charset));
77 }
78
79
80
81
82 public void addParam(String name, String value) {
83 if (name == null) {
84 throw new NullPointerException("name");
85 }
86 if (value == null) {
87 throw new NullPointerException("value");
88 }
89 params.add(new Param(name, value));
90 }
91
92
93
94
95
96
97 public URI toUri() throws URISyntaxException {
98 return new URI(toString());
99 }
100
101
102
103
104
105
106 @Override
107 public String toString() {
108 if (params.isEmpty()) {
109 return uri;
110 } else {
111 StringBuilder sb = new StringBuilder(uri).append('?');
112 for (int i = 0; i < params.size(); i++) {
113 Param param = params.get(i);
114 sb.append(encodeComponent(param.name, charset));
115 sb.append('=');
116 sb.append(encodeComponent(param.value, charset));
117 if (i != params.size() - 1) {
118 sb.append('&');
119 }
120 }
121 return sb.toString();
122 }
123 }
124
125 private static String encodeComponent(String s, Charset charset) {
126 try {
127 return URLEncoder.encode(s, charset.name()).replaceAll("\\+", "%20");
128 } catch (UnsupportedEncodingException e) {
129 throw new UnsupportedCharsetException(charset.name());
130 }
131 }
132
133 private static final class Param {
134
135 final String name;
136 final String value;
137
138 Param(String name, String value) {
139 this.value = value;
140 this.name = name;
141 }
142 }
143 }