Improve checking of JSON MIME in Java default and jersey2

to support suffix like charset in "application/json; charset=UTF8"
This commit is contained in:
xhh
2015-12-09 16:30:55 +08:00
parent 921659be5c
commit be0bc71c86
6 changed files with 164 additions and 46 deletions

View File

@@ -344,6 +344,17 @@ public class ApiClient {
return params;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
public boolean isJsonMime(String mime) {
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
@@ -354,8 +365,14 @@ public class ApiClient {
* null will be returned (not to set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) return null;
if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json";
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
@@ -369,8 +386,14 @@ public class ApiClient {
* JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) return "application/json";
if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json";
if (contentTypes.length == 0) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
@@ -390,7 +413,7 @@ public class ApiClient {
* Content-Type (only JSON is supported for now).
*/
public Entity<String> serialize(Object obj, String contentType) throws ApiException {
if (contentType.startsWith("application/json")) {
if (isJsonMime(contentType)) {
return Entity.json(json.serialize(obj));
} else {
throw new ApiException(400, "can not serialize object into Content-Type: " + contentType);
@@ -414,7 +437,7 @@ public class ApiClient {
else
body = "";
if (contentType.startsWith("application/json")) {
if (isJsonMime(contentType)) {
return json.deserialize(body, returnType);
} else if (returnType.getType().equals(String.class)) {
// Expecting string, return the raw response body.