Skip to content

Commit

Permalink
added utility methods for content type and charset
Browse files Browse the repository at this point in the history
  • Loading branch information
smartrics committed Dec 7, 2012
1 parent a63065e commit 13ab2c0
Showing 1 changed file with 34 additions and 16 deletions.
50 changes: 34 additions & 16 deletions src/main/java/smartrics/rest/client/RestData.java
Expand Up @@ -31,6 +31,7 @@
*/
public abstract class RestData {
public final static String LINE_SEPARATOR = System.getProperty("line.separator");
public static String DEFAULT_ENCODING = "UTF-8";

/**
* Holds an Http Header.
Expand Down Expand Up @@ -78,7 +79,6 @@ public String toString() {
private byte raw[];
private String resource;
private Long transactionId;
private String encoding = "UTF-8";

/**
* @return the body of this http request/response
Expand All @@ -88,28 +88,15 @@ public String getBody() {
return null;
}
try {
return new String(raw, encoding);
return new String(raw, getCharset());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unsupported encoding: " + encoding);
throw new IllegalStateException("Unsupported encoding: " + getCharset());
}
}

public byte[] getRawBody() {
return raw;
}

public void setEncoding(String enc) {
try {
new String(new byte[]{ 65 }, enc);
} catch(UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unsupported encoding: " + enc);
}
this.encoding = enc;
}

public String getEncoding() {
return encoding;
}

public RestData setBody(String body) {
if(body == null) {
Expand Down Expand Up @@ -254,4 +241,35 @@ public String toString() {
return builder.toString();
}

public String getContentType() {
return getHeaderValue("Content-Type");
}

public String getCharset() {
String v = getHeaderValue("Content-Type");
if(v == null || !v.contains("charset")) {
return DEFAULT_ENCODING;
}
int pos = v.indexOf("charset");
pos = v.indexOf("=", pos);
try {
String substring = v.substring(pos + 1);
return substring.trim();
} catch(RuntimeException e) {
return DEFAULT_ENCODING;
}
}

public String getContentLength() {
return getHeaderValue("Content-Length");
}

public String getHeaderValue(String name) {
List<Header> headers = getHeader(name);
if(headers.size() > 0) {
return headers.get(0).getValue();
}
return null;
}

}

0 comments on commit 13ab2c0

Please sign in to comment.