2 * Copyright (c) 2010-2020 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.apache.commons.io.IOUtils;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
29 * This class represents an {@link HttpRequest} response
31 * @author Tim Roberts - Initial contribution
34 public class HttpResponse {
36 /** The http status */
37 private final int httpStatus;
39 /** The http reason */
40 private final String httpReason;
42 /** The http headers */
43 private final Map<String, String> headers = new HashMap<>();
45 /** The contents as a raw byte array */
46 private final byte @Nullable [] contents;
49 * Instantiates a new http response from the {@link Response}.
51 * @param response the non-null response
52 * @throws IOException Signals that an I/O exception has occurred.
54 HttpResponse(Response response) throws IOException {
55 Objects.requireNonNull(response, "response cannot be null");
57 httpStatus = response.getStatus();
58 httpReason = response.getStatusInfo().getReasonPhrase();
60 if (response.hasEntity()) {
61 InputStream is = response.readEntity(InputStream.class);
62 contents = IOUtils.toByteArray(is);
67 for (String key : response.getHeaders().keySet()) {
68 headers.put(key, response.getHeaderString(key));
73 * Instantiates a new http response.
75 * @param httpCode the http code
78 HttpResponse(int httpCode, String msg) {
79 httpStatus = httpCode;
85 * Gets the HTTP status code.
87 * @return the HTTP status code
89 public int getHttpCode() {
98 public String getContent() {
99 final byte[] localContents = contents;
100 if (localContents == null || localContents.length == 0) {
104 return new String(localContents, StandardCharsets.UTF_8);
108 * Creates an {@link IOException} from the {@link #httpReason}
110 * @return the IO exception
112 public IOException createException() {
113 return new IOException(httpReason);
117 public String toString() {
118 return getHttpCode() + " (" + (contents == null ? ("http reason: " + httpReason) : getContent()) + ")";