1 32 package org.apache.commons.httpclient.methods; 33 34 import java.io.IOException ; 35 import java.io.OutputStream ; 36 import java.io.UnsupportedEncodingException ; 37 38 import org.apache.commons.httpclient.HeaderElement; 39 import org.apache.commons.httpclient.NameValuePair; 40 41 46 public class StringRequestEntity implements RequestEntity { 47 48 49 private byte[] content; 50 51 52 private String charset; 53 54 55 private String contentType; 56 57 68 public StringRequestEntity(String content) { 69 super(); 70 if (content == null) { 71 throw new IllegalArgumentException ("The content cannot be null"); 72 } 73 this.contentType = null; 74 this.charset = null; 75 this.content = content.getBytes(); 76 } 77 78 89 public StringRequestEntity(String content, String contentType, String charset) 90 throws UnsupportedEncodingException { 91 super(); 92 if (content == null) { 93 throw new IllegalArgumentException ("The content cannot be null"); 94 } 95 96 this.contentType = contentType; 97 this.charset = charset; 98 99 if (contentType != null) { 101 HeaderElement[] values = HeaderElement.parseElements(contentType); 102 NameValuePair charsetPair = null; 103 for (int i = 0; i < values.length; i++) { 104 if ((charsetPair = values[i].getParameterByName("charset")) != null) { 105 break; 107 } 108 } 109 if (charset == null && charsetPair != null) { 110 this.charset = charsetPair.getValue(); 112 } else if (charset != null && charsetPair == null) { 113 this.contentType = contentType + "; charset=" + charset; 115 } 116 } 117 if (this.charset != null) { 118 this.content = content.getBytes(this.charset); 119 } else { 120 this.content = content.getBytes(); 121 } 122 } 123 124 127 public String getContentType() { 128 return contentType; 129 } 130 131 134 public boolean isRepeatable() { 135 return true; 136 } 137 138 141 public void writeRequest(OutputStream out) throws IOException { 142 if (out == null) { 143 throw new IllegalArgumentException ("Output stream may not be null"); 144 } 145 out.write(this.content); 146 out.flush(); 147 } 148 149 152 public long getContentLength() { 153 return this.content.length; 154 } 155 156 159 public String getContent() { 160 if (this.charset != null) { 161 try { 162 return new String (this.content, this.charset); 163 } catch (UnsupportedEncodingException e) { 164 return new String (this.content); 165 } 166 } else { 167 return new String (this.content); 168 } 169 } 170 171 175 public String getCharset() { 176 return charset; 177 } 178 } 179 | Popular Tags |