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 java.nio.charset.Charsets;
23import libcore.net.UriCodec;
24
25/**
26 * This class is used to encode a string using the format required by
27 * {@code application/x-www-form-urlencoded} MIME content type.
28 *
29 * <p>All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9')
30 * and characters '.', '-', '*', '_' are converted into their hexadecimal value
31 * prepended by '%'. For example: '#' -> %23. In addition, spaces are
32 * substituted by '+'.
33 */
34public class URLEncoder {
35    private URLEncoder() {}
36
37    static UriCodec ENCODER = new UriCodec() {
38        @Override protected boolean isRetained(char c) {
39            return " .-*_".indexOf(c) != -1;
40        }
41    };
42
43    /**
44     * Equivalent to {@code encode(s, "UTF-8")}.
45     *
46     * @deprecated use {@link #encode(String, String)} instead.
47     */
48    @Deprecated
49    public static String encode(String s) {
50        return ENCODER.encode(s, Charsets.UTF_8);
51    }
52
53    /**
54     * Encodes {@code s} using the {@link Charset} named by {@code charsetName}.
55     */
56    public static String encode(String s, String charsetName) throws UnsupportedEncodingException {
57        return ENCODER.encode(s, Charset.forName(charsetName));
58    }
59}
60