Java tutorial
/* * This file is part of ChangePurse. * * Copyright (c) 2014 Germn Fuentes Capella * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package bit.changepurse.wdk.http; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import bit.changepurse.wdk.util.CheckedExceptionMethods; public class HTTPResponse { private static final int MAX_LENGTH_BODY_TO_STRING = 4000; private final HTTPStatusCode statusCode; private final String location; private final String body; public HTTPResponse(CloseableHttpResponse apacheResponse) { statusCode = getStatusCode(apacheResponse); location = getFromHeaders(apacheResponse, "Location"); body = getBody(apacheResponse); } private String getBody(CloseableHttpResponse apacheResponse) { HttpEntity entity = apacheResponse.getEntity(); return CheckedExceptionMethods.toString(entity); } private String getFromHeaders(CloseableHttpResponse apacheResponse, String key) { Header[] headers = apacheResponse.getHeaders(key); if (headers != null) { if (headers.length >= 1) { return headers[0].getValue(); } } return ""; } private HTTPStatusCode getStatusCode(CloseableHttpResponse apacheResponse) { StatusLine statusLine = apacheResponse.getStatusLine(); return HTTPStatusCode.fromInt(statusLine.getStatusCode()); } public HTTPStatusCode getStatusCode() { return statusCode; } public String getLocationFromHeaders() { return location; } public String getBody() { return body; } @Override public String toString() { String content = ""; if (body != null) { if (body.length() > MAX_LENGTH_BODY_TO_STRING) { content = body.substring(0, MAX_LENGTH_BODY_TO_STRING) + "..."; } else { content = body; } } return statusCode.name() + " " + content; } }