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.nio.charset.StandardCharsets;
17 import java.util.HashMap;
19 import java.util.Objects;
21 import javax.ws.rs.core.Response;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.eclipse.jetty.client.api.ContentResponse;
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 refreshResponse the non-null response
51 * @throws IOException Signals that an I/O exception has occurred.
53 HttpResponse(ContentResponse refreshResponse) throws IOException {
54 Objects.requireNonNull(refreshResponse, "response cannot be null");
56 httpStatus = refreshResponse.getStatus();
57 httpReason = refreshResponse.getReason();
58 contents = refreshResponse.getContent();
60 for (String key : refreshResponse.getHeaders().getFieldNamesCollection()) {
61 headers.put(key, refreshResponse.getHeaders().getField(key).toString());
66 * Instantiates a new http response.
68 * @param httpCode the http code
71 HttpResponse(int httpCode, @Nullable String msg) {
72 httpStatus = httpCode;
73 httpReason = msg != null ? msg : "";
78 * Gets the HTTP status code.
80 * @return the HTTP status code
82 public int getHttpCode() {
91 public String getContent() {
92 final byte[] localContents = contents;
93 if (localContents == null || localContents.length == 0) {
97 return new String(localContents, StandardCharsets.UTF_8);
101 * Creates an {@link IOException} from the {@link #httpReason}
103 * @return the IO exception
105 public IOException createException() {
106 return new IOException(httpReason);
110 public String toString() {
111 return getHttpCode() + " (" + (contents == null ? ("http reason: " + httpReason) : getContent()) + ")";