1 /*
2 * This file is part of dependency-check-utils.
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 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * Copyright (c) 2024 Hans Aikema. All Rights Reserved.
17 */
18 package org.owasp.dependencycheck.utils;
19
20 import org.apache.hc.client5.http.impl.classic.AbstractHttpClientResponseHandler;
21 import org.apache.hc.core5.http.HttpEntity;
22 import org.apache.hc.core5.http.io.entity.EntityUtils;
23
24 import java.io.IOException;
25 import java.nio.charset.Charset;
26
27 /**
28 * A responseHandler that uses an explicit client-defined characterset to interpret the response payload as a string.
29 *
30 * @author Hans Aikema
31 */
32 public class ExplicitEncodingToStringResponseHandler extends AbstractHttpClientResponseHandler<String> {
33
34 /**
35 * The explicit Charset used for interpreting the bytes of the HTTP response entity.
36 */
37 private final Charset charset;
38
39 /**
40 * Constructs a repsonse handler to transfor the binary contents received using the given Charset.
41 *
42 * @param charset The Charset to be used to transform a downloaded file into a String.
43 */
44 public ExplicitEncodingToStringResponseHandler(Charset charset) {
45 this.charset = charset;
46 }
47
48 @Override
49 public String handleEntity(HttpEntity entity) throws IOException {
50 return new String(EntityUtils.toByteArray(entity), charset);
51 }
52 }