001/*
002 *   Copyright 2020 Vonage
003 *
004 *   Licensed under the Apache License, Version 2.0 (the "License");
005 *   you may not use this file except in compliance with the License.
006 *   You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *   Unless required by applicable law or agreed to in writing, software
011 *   distributed under the License is distributed on an "AS IS" BASIS,
012 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *   See the License for the specific language governing permissions and
014 *   limitations under the License.
015 */
016package com.vonage.client.logging;
017
018import org.apache.http.HttpResponse;
019import org.apache.http.entity.ContentType;
020import org.apache.http.entity.StringEntity;
021import org.apache.http.util.EntityUtils;
022
023import java.io.IOException;
024
025public class LoggingUtils {
026
027    public static String logResponse(HttpResponse response) throws IOException {
028        StringBuilder log = new StringBuilder();
029        String responseBody = EntityUtils.toString(response.getEntity());
030        int statusCode = response.getStatusLine().getStatusCode();
031        String statusLine = response.getStatusLine().getReasonPhrase();
032
033        log.append("status_code: ")
034                .append(statusCode)
035                .append( ", ")
036                .append("status_line: ")
037                .append(statusLine)
038                .append(", ")
039                .append(" body: ")
040                .append(responseBody);
041
042        //Calling Http#getEntity will consume the entity so you have to replace the entity after logging
043        response.setEntity(new StringEntity(responseBody, ContentType.get(response.getEntity())));
044
045        return log.toString();
046    }
047}