com.sigopt.net.Requester Maven / Gradle / Ivy
package com.sigopt.net;
import com.squareup.okhttp.*;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.*;
public class Requester {
public static final String CHARSET = "UTF-8";
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
public static OkHttpClient client = new OkHttpClient();
public static class Response {
public String body;
public Integer code;
public Response(String body, Integer code) {
this.body = body;
this.code = code;
}
}
public static Response request(String method, String url, Map params, Map headers) throws Exception {
com.squareup.okhttp.Response res = client.newCall(createRequest(method, url, params, headers)).execute();
return new Response(res.body().string(), res.code());
}
public static Request createRequest(String method, String url, Map params, Map headers) throws Exception {
Request.Builder rb = new Request.Builder();
RequestBody reqBody = composeRequestBody(params);
method = method.toLowerCase();
if(method.equals("get")) {
rb = rb.get();
url = composeUrlEncodedUrl(url, params);
} else if(method.equals("delete")) {
rb = rb.delete();
url = composeUrlEncodedUrl(url, params);
} else if (method.equals("post")) {
rb = rb.post(reqBody);
} else if(method.equals("put")) {
rb = rb.put(reqBody);
} else {
throw new Exception("Invalid Method Type: " + method);
}
for(Map.Entry entry : headers.entrySet()) {
rb = rb.header(entry.getKey(), entry.getValue());
}
Request req = rb.url(url).build();
return req;
}
static String composeUrlEncodedUrl(String url, Map params) {
String urlSuffix = mapToUrlEncodedString(params);
if(url.contains("?")) {
url = url + "&" + urlSuffix;
} else {
url = url + "?" + urlSuffix;
}
return url;
}
static RequestBody composeRequestBody(Map params) {
if(params.size() == 0) {
return null;
}
FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
List list = mapToKeyValueList(params);
for(KeyValue kv : list) {
formBodyBuilder = formBodyBuilder.add(kv.key, kv.value);
}
return formBodyBuilder.build();
}
static String mapToUrlEncodedString(Map map) {
StringBuilder ret = new StringBuilder();
List list = mapToKeyValueList(map);
for(KeyValue kv : list) {
ret.append(kv.toString() + "&");
}
return ret.substring(0, ret.length() - 1);
}
static List