1 /*
2 * Copyright (c) 2002-2025 Gargoyle Software Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 package org.htmlunit.protocol.data;
16
17 import java.io.ByteArrayInputStream;
18 import java.io.InputStream;
19 import java.io.UnsupportedEncodingException;
20 import java.net.URL;
21 import java.net.URLConnection;
22
23 /**
24 * A URLConnection for supporting data URLs.
25 * @see <a href="http://www.ietf.org/rfc/rfc2397.txt">RFC2397</a>
26 * @author Marc Guillemot
27 * @author Ronald Brill
28 */
29 public class DataURLConnection extends URLConnection {
30
31 /** The "URL" prefix 'data:'. */
32 public static final String DATA_PREFIX = "data:";
33
34 private final DataUrlDecoder dataUrlDecoder_;
35
36 /**
37 * Creates an instance.
38 * @param url the data URL
39 * @throws UnsupportedEncodingException in case the encoding is not supported
40 */
41 public DataURLConnection(final URL url) throws UnsupportedEncodingException {
42 super(url);
43 dataUrlDecoder_ = DataUrlDecoder.decode(url);
44 }
45
46 /**
47 * This method does nothing in this implementation but is required to be implemented.
48 */
49 @Override
50 public void connect() {
51 // Empty.
52 }
53
54 /**
55 * Returns the input stream - in this case the content of the URL.
56 * @return the input stream
57 */
58 @Override
59 public InputStream getInputStream() {
60 return new ByteArrayInputStream(dataUrlDecoder_.getBytes());
61 }
62
63 /**
64 * Gets the charset information specified in the data URL.
65 * @return "US-ASCII" if the URL didn't contain any charset information
66 */
67 public String getCharset() {
68 return dataUrlDecoder_.getCharset();
69 }
70
71 /**
72 * Gets the media type information contained in the data URL.
73 * @return "text/plain" if the URL didn't contain any media type information
74 */
75 public String getMediaType() {
76 return dataUrlDecoder_.getMediaType();
77 }
78 }