2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.neeo.internal.net;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.nio.charset.StandardCharsets;
18 import java.util.HashMap;
20 import java.util.Objects;
22 import javax.ws.rs.core.Response;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
28 * This class represents an {@link HttpRequest} response
30 * @author Tim Roberts - Initial contribution
33 public class HttpResponse {
35 /** The http status */
36 private final int httpStatus;
38 /** The http reason */
39 private final String httpReason;
41 /** The http headers */
42 private final Map<String, String> headers = new HashMap<>();
44 /** The contents as a raw byte array */
45 private final byte @Nullable [] contents;
48 * Instantiates a new http response from the {@link Response}.
50 * @param response the non-null response
51 * @throws IOException Signals that an I/O exception has occurred.
53 HttpResponse(Response response) throws IOException {
54 Objects.requireNonNull(response, "response cannot be null");
56 httpStatus = response.getStatus();
57 httpReason = response.getStatusInfo().getReasonPhrase();
59 if (response.hasEntity()) {
60 InputStream is = response.readEntity(InputStream.class);
61 contents = is.readAllBytes();
66 for (String key : response.getHeaders().keySet()) {
67 headers.put(key, response.getHeaderString(key));
72 * Instantiates a new http response.
74 * @param httpCode the http code
77 HttpResponse(int httpCode, @Nullable String msg) {
78 httpStatus = httpCode;
79 httpReason = msg != null ? msg : "";
84 * Gets the HTTP status code.
86 * @return the HTTP status code
88 public int getHttpCode() {
97 public String getContent() {
98 final byte[] localContents = contents;
99 if (localContents == null || localContents.length == 0) {
103 return new String(localContents, StandardCharsets.UTF_8);
107 * Creates an {@link IOException} from the {@link #httpReason}
109 * @return the IO exception
111 public IOException createException() {
112 return new IOException(httpReason);
116 public String toString() {
117 return getHttpCode() + " (" + (contents == null ? ("http reason: " + httpReason) : getContent()) + ")";