001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.http.entity; 018 019 020import java.io.*; 021import java.nio.charset.*; 022 023import org.apache.juneau.http.*; 024import static org.apache.juneau.commons.utils.Shorts.*; 025 026/** 027 * An {@link HttpBody} backed by a UTF-8 string. 028 * 029 * <p> 030 * Repeatable: the same instance may be written multiple times. 031 * 032 * @since 9.2.1 033 */ 034public final class StringBody implements HttpBody { 035 036 private final String content; 037 private final String contentType; 038 private final byte[] bytes; 039 040 private StringBody(String content, String contentType) { 041 this.content = reqnn("content", content); 042 this.contentType = contentType; 043 this.bytes = content.getBytes(StandardCharsets.UTF_8); 044 } 045 046 /** 047 * Creates a {@link StringBody} with the given content and {@code text/plain; charset=UTF-8} content type. 048 * 049 * @param content The string content. Must not be <jk>null</jk>. 050 * @return A new instance. Never <jk>null</jk>. 051 */ 052 public static StringBody of(String content) { 053 return new StringBody(content, "text/plain; charset=UTF-8"); 054 } 055 056 /** 057 * Creates a {@link StringBody} with the given content and content type. 058 * 059 * @param content The string content. Must not be <jk>null</jk>. 060 * @param contentType The MIME content type (e.g. {@code "application/json; charset=UTF-8"}). May be <jk>null</jk>. 061 * @return A new instance. Never <jk>null</jk>. 062 */ 063 public static StringBody of(String content, String contentType) { 064 return new StringBody(content, contentType); 065 } 066 067 @Override /* HttpBody */ 068 public String getContentType() { 069 return contentType; 070 } 071 072 @Override /* HttpBody */ 073 public long getContentLength() { 074 return bytes.length; 075 } 076 077 @Override /* HttpBody */ 078 public void writeTo(OutputStream out) throws IOException { 079 out.write(bytes); 080 } 081 082 @Override /* HttpBody */ 083 public boolean isRepeatable() { 084 return true; 085 } 086 087 @Override /* Object */ 088 public String toString() { 089 return content; 090 } 091}