URLEncoder.java revision 56099d23fcb002b164bff8fb7f14d6ec0453509e
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package java.net;
19
20import java.io.UnsupportedEncodingException;
21import java.nio.charset.Charset;
22import libcore.net.UriCodec;
23
24/**
25 * This class is used to encode a string using the format required by
26 * {@code application/x-www-form-urlencoded} MIME content type.
27 *
28 * <p>All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
29 * and characters '.', '-', '*', '_' are converted into their hexadecimal value
30 * prepended by '%'. For example: '#' -> %23. In addition, spaces are
31 * substituted by '+'.
32 */
33public class URLEncoder {
34    private URLEncoder() {}
35
36    static UriCodec ENCODER = new UriCodec() {
37        @Override protected boolean isRetained(char c) {
38            return " .-*_".indexOf(c) != -1;
39        }
40    };
41
42    /**
43     * Equivalent to {@code encode(s, "UTF-8")}.
44     *
45     * @deprecated use {@link #encode(String, String)} instead.
46     */
47    @Deprecated
48    public static String encode(String s) {
49        try {
50            return encode(s, "UTF-8");
51        } catch (UnsupportedEncodingException e) {
52            throw new AssertionError();
53        }
54    }
55
56    /**
57     * Encodes {@code s} using the {@link Charset} named by {@code charsetName}.
58     */
59    public static String encode(String s, String charsetName) throws UnsupportedEncodingException {
60        // Guess a bit larger for encoded form
61        StringBuilder builder = new StringBuilder(s.length() + 16);
62        ENCODER.appendEncoded(builder, s, Charset.forName(charsetName));
63        return builder.toString();
64    }
65}
66