Add support of form parameter to Android client

* Handle form parameters in a way similar to Java client.
* Handle file uploading.
* Normalize query, header and form parameters with the
  ApiInvoker.parameterToString method, which formats Date value to ISO 8601.
This commit is contained in:
xhh
2015-03-21 22:20:28 +08:00
parent 9062016bf0
commit b5a4d5be04
8 changed files with 703 additions and 84 deletions

View File

@@ -10,6 +10,9 @@ import java.util.*;
{{#imports}}import {{import}};
{{/imports}}
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
@@ -55,19 +58,46 @@ public class {{classname}} {
// query params
Map<String, String> queryParams = new HashMap<String, String>();
// header params
Map<String, String> headerParams = new HashMap<String, String>();
// form params
Map<String, String> formParams = new HashMap<String, String>();
{{#queryParams}}if(!"null".equals(String.valueOf({{paramName}})))
queryParams.put("{{baseName}}", String.valueOf({{paramName}}));
{{#queryParams}}if ({{paramName}} != null)
queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/queryParams}}
{{#headerParams}}headerParams.put("{{baseName}}", {{paramName}});
{{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));
{{/headerParams}}
String contentType = "application/json";
String[] contentTypes = {
{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}
};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if (contentType.startsWith("multipart/form-data")) {
// file uploading
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
{{#formParams}}{{#notFile}}
if ({{paramName}} != null) {
builder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8);
}
{{/notFile}}{{#isFile}}
if ({{paramName}} != null) {
builder.addBinaryBody("{{baseName}}", {{paramName}});
}
{{/isFile}}{{/formParams}}
HttpEntity httpEntity = builder.build();
postBody = httpEntity;
} else {
// normal form params
{{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}}
{{/formParams}}
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, contentType);
String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}};
}

View File

@@ -12,6 +12,7 @@ import org.apache.http.client.methods.*;
import org.apache.http.conn.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.*;
@@ -40,6 +41,7 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -61,6 +63,61 @@ public class ApiInvoker {
private ClientConnectionManager ignoreSSLConnectionManager;
/** Content type "text/plain" with UTF-8 encoding. */
public static final ContentType TEXT_PLAIN_UTF8 = ContentType.create("text/plain", Consts.UTF_8);
/**
* ISO 8601 date time format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
/**
* ISO 8601 date format.
* @see https://en.wikipedia.org/wiki/ISO_8601
*/
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
static {
// Use UTC as the default time zone.
DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public static Date parseDateTime(String str) {
try {
return DATE_TIME_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static Date parseDate(String str) {
try {
return DATE_FORMAT.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
public static String formatDateTime(Date datetime) {
return DATE_TIME_FORMAT.format(datetime);
}
public static String formatDate(Date date) {
return DATE_FORMAT.format(date);
}
public static String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDateTime((Date) param);
} else {
return String.valueOf(param);
}
}
public ApiInvoker() {
initConnectionManager();
}
@@ -91,7 +148,7 @@ public class ApiInvoker {
else if(String.class.equals(cls)) {
if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1)
return json.substring(1, json.length() - 2);
else
else
return json;
}
else {
@@ -105,9 +162,9 @@ public class ApiInvoker {
public static String serialize(Object obj) throws ApiException {
try {
if (obj != null)
if (obj != null)
return JsonUtil.getJsonMapper().writeValueAsString(obj);
else
else
return null;
}
catch (Exception e) {
@@ -115,7 +172,7 @@ public class ApiInvoker {
}
}
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, String contentType) throws ApiException {
public String invokeAPI(String host, String path, String method, Map<String, String> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType) throws ApiException {
HttpClient client = getClient(host);
StringBuilder b = new StringBuilder();
@@ -136,7 +193,7 @@ public class ApiInvoker {
for(String key : headerParams.keySet()) {
headers.put(key, headerParams.get(key));
}
for(String key : defaultHeaderMap.keySet()) {
if(!headerParams.containsKey(key)) {
headers.put(key, defaultHeaderMap.get(key));
@@ -144,9 +201,34 @@ public class ApiInvoker {
}
headers.put("Accept", "application/json");
// URL encoded string from form parameters
String formParamStr = null;
// for form data
if ("application/x-www-form-urlencoded".equals(contentType)) {
StringBuilder formParamBuilder = new StringBuilder();
// encode the form params
for (String key : formParams.keySet()) {
String value = formParams.get(key);
if (value != null && !"".equals(value.trim())) {
if (formParamBuilder.length() > 0) {
formParamBuilder.append("&");
}
try {
formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8"));
}
catch (Exception e) {
// move on to next
}
}
}
formParamStr = formParamBuilder.toString();
}
HttpResponse response = null;
try{
if("GET".equals(method)) {
try {
if ("GET".equals(method)) {
HttpGet get = new HttpGet(url);
get.addHeader("Accept", "application/json");
for(String key : headers.keySet()) {
@@ -156,10 +238,17 @@ public class ApiInvoker {
}
else if ("POST".equals(method)) {
HttpPost post = new HttpPost(url);
if (body != null) {
if (formParamStr != null) {
post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(serialize(body), "UTF-8"));
post.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) {
if (body instanceof HttpEntity) {
// this is for file uploading
post.setEntity((HttpEntity) body);
} else {
post.setHeader("Content-Type", contentType);
post.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
}
for(String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
@@ -168,7 +257,10 @@ public class ApiInvoker {
}
else if ("PUT".equals(method)) {
HttpPut put = new HttpPut(url);
if(body != null) {
if (formParamStr != null) {
put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) {
put.setHeader("Content-Type", contentType);
put.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
@@ -186,8 +278,10 @@ public class ApiInvoker {
}
else if ("PATCH".equals(method)) {
HttpPatch patch = new HttpPatch(url);
if (body != null) {
if (formParamStr != null) {
patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(formParamStr, "UTF-8"));
} else if (body != null) {
patch.setHeader("Content-Type", contentType);
patch.setEntity(new StringEntity(serialize(body), "UTF-8"));
}
@@ -199,7 +293,7 @@ public class ApiInvoker {
int code = response.getStatusLine().getStatusCode();
String responseString = null;
if(code == 204)
if(code == 204)
responseString = "";
else if(code >= 200 && code < 300) {
if(response.getEntity() != null) {

View File

@@ -136,6 +136,12 @@
<version>${httpclient-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpclient-version}</version>
<scope>compile</scope>
</dependency>
<!-- test dependencies -->
<dependency>
@@ -157,6 +163,6 @@
<junit-version>4.8.1</junit-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.8.1</junit-version>
<httpclient-version>4.0</httpclient-version>
<httpclient-version>4.3.6</httpclient-version>
</properties>
</project>