001/* 002 * Copyright 2002-2014 the original author or authors. 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 * https://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 */ 016 017package org.springframework.mock.http; 018 019import java.io.ByteArrayOutputStream; 020import java.io.IOException; 021import java.io.OutputStream; 022import java.io.UnsupportedEncodingException; 023import java.nio.charset.Charset; 024 025import org.springframework.http.HttpHeaders; 026import org.springframework.http.HttpOutputMessage; 027 028/** 029 * Mock implementation of {@link HttpOutputMessage}. 030 * 031 * @author Rossen Stoyanchev 032 * @since 3.2 033 */ 034public class MockHttpOutputMessage implements HttpOutputMessage { 035 036 private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); 037 038 private final HttpHeaders headers = new HttpHeaders(); 039 040 private final ByteArrayOutputStream body = new ByteArrayOutputStream(1024); 041 042 043 /** 044 * Return the headers. 045 */ 046 @Override 047 public HttpHeaders getHeaders() { 048 return this.headers; 049 } 050 051 /** 052 * Return the body content. 053 */ 054 @Override 055 public OutputStream getBody() throws IOException { 056 return this.body; 057 } 058 059 /** 060 * Return body content as a byte array. 061 */ 062 public byte[] getBodyAsBytes() { 063 return this.body.toByteArray(); 064 } 065 066 /** 067 * Return the body content interpreted as a UTF-8 string. 068 */ 069 public String getBodyAsString() { 070 return getBodyAsString(DEFAULT_CHARSET); 071 } 072 073 /** 074 * Return the body content as a string. 075 * @param charset the charset to use to turn the body content to a String 076 */ 077 public String getBodyAsString(Charset charset) { 078 byte[] bytes = getBodyAsBytes(); 079 try { 080 return new String(bytes, charset.name()); 081 } 082 catch (UnsupportedEncodingException ex) { 083 // should not occur 084 throw new IllegalStateException(ex); 085 } 086 } 087 088}