1 package com.foxinmy.weixin4j.http.entity; 2 3 import java.io.ByteArrayInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 8 import com.foxinmy.weixin4j.http.ContentType; 9 import com.foxinmy.weixin4j.util.Consts; 10 11 public class StringEntity implements HttpEntity { 12 13 private final byte[] content; 14 private final ContentType contentType; 15 16 public StringEntity(String body) { 17 this(body, ContentType.DEFAULT_TEXT); 18 } 19 20 public StringEntity(String body, ContentType contentType) { 21 this.content = body.getBytes(contentType.getCharset()); 22 this.contentType = contentType; 23 } 24 25 @Override 26 public ContentType getContentType() { 27 return contentType; 28 } 29 30 @Override 31 public long getContentLength() { 32 return this.content.length; 33 } 34 35 @Override 36 public InputStream getContent() throws IOException { 37 return new ByteArrayInputStream(this.content); 38 } 39 40 @Override 41 public void writeTo(OutputStream outstream) throws IOException { 42 outstream.write(this.content); 43 outstream.flush(); 44 } 45 46 47 public String getContentString() { 48 return new String(this.content, Consts.UTF_8); 49 } 50 51 }