1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http;
17
18 import io.netty.util.internal.ObjectUtil;
19
20 import java.io.UnsupportedEncodingException;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.net.URLEncoder;
24 import java.nio.charset.Charset;
25 import java.nio.charset.UnsupportedCharsetException;
26
27
28
29
30
31
32
33
34
35
36
37
38 public class QueryStringEncoder {
39
40 private final String charsetName;
41 private final StringBuilder uriBuilder;
42 private boolean hasParams;
43
44
45
46
47
48 public QueryStringEncoder(String uri) {
49 this(uri, HttpConstants.DEFAULT_CHARSET);
50 }
51
52
53
54
55
56 public QueryStringEncoder(String uri, Charset charset) {
57 uriBuilder = new StringBuilder(uri);
58 charsetName = charset.name();
59 }
60
61
62
63
64 public void addParam(String name, String value) {
65 ObjectUtil.checkNotNull(name, "name");
66 if (hasParams) {
67 uriBuilder.append('&');
68 } else {
69 uriBuilder.append('?');
70 hasParams = true;
71 }
72 appendComponent(name, charsetName, uriBuilder);
73 if (value != null) {
74 uriBuilder.append('=');
75 appendComponent(value, charsetName, uriBuilder);
76 }
77 }
78
79
80
81
82
83
84 public URI toUri() throws URISyntaxException {
85 return new URI(toString());
86 }
87
88
89
90
91
92
93 @Override
94 public String toString() {
95 return uriBuilder.toString();
96 }
97
98 private static void appendComponent(String s, String charset, StringBuilder sb) {
99 try {
100 s = URLEncoder.encode(s, charset);
101 } catch (UnsupportedEncodingException ignored) {
102 throw new UnsupportedCharsetException(charset);
103 }
104
105 int idx = s.indexOf('+');
106 if (idx == -1) {
107 sb.append(s);
108 return;
109 }
110 sb.append(s, 0, idx).append("%20");
111 int size = s.length();
112 idx++;
113 for (; idx < size; idx++) {
114 char c = s.charAt(idx);
115 if (c != '+') {
116 sb.append(c);
117 } else {
118 sb.append("%20");
119 }
120 }
121 }
122 }