OKHttpUtil.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. package cn.com.qmth.examcloud.commons.util;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.Map.Entry;
  6. import java.util.concurrent.TimeUnit;
  7. import org.apache.commons.collections.CollectionUtils;
  8. import cn.com.qmth.examcloud.commons.helpers.FormFilePart;
  9. import cn.com.qmth.examcloud.commons.logging.ExamCloudLog;
  10. import cn.com.qmth.examcloud.commons.logging.ExamCloudLogFactory;
  11. import okhttp3.FormBody;
  12. import okhttp3.MediaType;
  13. import okhttp3.MultipartBody;
  14. import okhttp3.OkHttpClient;
  15. import okhttp3.Request;
  16. import okhttp3.Request.Builder;
  17. import okhttp3.RequestBody;
  18. import okhttp3.Response;
  19. /**
  20. * OKHttp
  21. *
  22. * @author WANGWEI
  23. * @date 2018年9月6日
  24. * @Copyright (c) 2018-2020 http://www.qmth.com.cn/ All Rights Reserved.
  25. */
  26. public class OKHttpUtil {
  27. private static final ExamCloudLog LOG = ExamCloudLogFactory.getLog(OKHttpUtil.class);
  28. public static final class MediaTypes {
  29. public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  30. }
  31. /**
  32. * 请求体构建器
  33. *
  34. * @author WANGWEI
  35. * @date 2019年4月10日
  36. * @Copyright (c) 2018-2020 http://www.qmth.com.cn/ All Rights Reserved.
  37. */
  38. public static interface RequestBodyBuilder {
  39. RequestBody build();
  40. }
  41. /**
  42. * json请求体构建器
  43. *
  44. * @author WANGWEI
  45. * @date 2019年4月10日
  46. * @Copyright (c) 2018-2020 http://www.qmth.com.cn/ All Rights Reserved.
  47. */
  48. public static final class JsonBodyBuilder implements RequestBodyBuilder {
  49. private String json;
  50. public JsonBodyBuilder(String json) {
  51. super();
  52. this.json = json;
  53. }
  54. @Override
  55. public RequestBody build() {
  56. return RequestBody.create(MediaTypes.JSON, json);
  57. }
  58. @Override
  59. public String toString() {
  60. return json;
  61. }
  62. }
  63. private static OkHttpClient okHttpClient;
  64. static {
  65. okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
  66. .readTimeout(20, TimeUnit.SECONDS).build();
  67. }
  68. public static OkHttpClient getOkHttpClient() {
  69. return okHttpClient;
  70. }
  71. /**
  72. * 发送请求 (带json请求体)
  73. *
  74. * @author WANGWEI
  75. * @param httpMethod
  76. * @param url
  77. * @param headers
  78. * @param jsonBody
  79. * @return
  80. */
  81. public static Response call(HttpMethod httpMethod, String url, Map<String, String> headers,
  82. String jsonBody) {
  83. return call(httpMethod, url, headers, new JsonBodyBuilder(jsonBody));
  84. }
  85. /**
  86. * 发送请求 (带请求体)
  87. *
  88. * @author WANGWEI
  89. * @param httpMethod
  90. * @param url
  91. * @param headers
  92. * @param requestBodyBuilder
  93. * @return
  94. */
  95. public static Response call(HttpMethod httpMethod, String url, Map<String, String> headers,
  96. RequestBodyBuilder requestBodyBuilder) {
  97. LOG.info("[okhttp3] new call: " + httpMethod + " " + url);
  98. LOG.info("[okhttp3] headers: " + JsonUtil.toJson(headers));
  99. LOG.info("[okhttp3] body: " + requestBodyBuilder);
  100. Builder builder = null;
  101. if (httpMethod.equals(HttpMethod.GET)) {
  102. builder = new Request.Builder().url(url).get();
  103. } else if (httpMethod.equals(HttpMethod.POST)) {
  104. builder = new Request.Builder().url(url).post(requestBodyBuilder.build());
  105. } else if (httpMethod.equals(HttpMethod.PUT)) {
  106. builder = new Request.Builder().url(url).put(requestBodyBuilder.build());
  107. } else if (httpMethod.equals(HttpMethod.DELETE)) {
  108. builder = new Request.Builder().url(url).delete(requestBodyBuilder.build());
  109. }
  110. if (null != headers && 0 != headers.size()) {
  111. for (Entry<String, String> entry : headers.entrySet()) {
  112. builder.addHeader(entry.getKey(), entry.getValue());
  113. }
  114. }
  115. Request request = builder.build();
  116. Response response = null;
  117. try {
  118. response = okHttpClient.newCall(request).execute();
  119. return response;
  120. } catch (IOException e) {
  121. throw new RuntimeException(e);
  122. }
  123. }
  124. /**
  125. * 发送请求
  126. *
  127. * @author WANGWEI
  128. * @param httpMethod
  129. * @param url
  130. * @return
  131. */
  132. public static Response call(HttpMethod httpMethod, String url) {
  133. return call(httpMethod, url, null);
  134. }
  135. /**
  136. * 发送请求
  137. *
  138. * @author WANGWEI
  139. * @param httpMethod
  140. * @param url
  141. * @param headers
  142. * @return
  143. */
  144. public static Response call(HttpMethod httpMethod, String url, Map<String, String> headers) {
  145. LOG.info("[okhttp3] new call: " + httpMethod + " " + url);
  146. LOG.info("[okhttp3] headers: " + JsonUtil.toJson(headers));
  147. Builder builder = null;
  148. if (httpMethod.equals(HttpMethod.GET)) {
  149. builder = new Request.Builder().url(url).get();
  150. } else if (httpMethod.equals(HttpMethod.POST)) {
  151. builder = new Request.Builder().url(url).post(new FormBody.Builder().build());
  152. } else if (httpMethod.equals(HttpMethod.PUT)) {
  153. builder = new Request.Builder().url(url).put(new FormBody.Builder().build());
  154. } else if (httpMethod.equals(HttpMethod.DELETE)) {
  155. builder = new Request.Builder().url(url).delete(new FormBody.Builder().build());
  156. }
  157. if (null != headers && 0 != headers.size()) {
  158. for (Entry<String, String> entry : headers.entrySet()) {
  159. builder.addHeader(entry.getKey(), entry.getValue());
  160. }
  161. }
  162. Request request = builder.build();
  163. Response response = null;
  164. try {
  165. response = okHttpClient.newCall(request).execute();
  166. return response;
  167. } catch (IOException e) {
  168. throw new RuntimeException(e);
  169. }
  170. }
  171. /**
  172. * 发送请求 (表单)
  173. *
  174. * @author WANGWEI
  175. * @param httpMethod
  176. * @param url
  177. * @param headers
  178. * @param params
  179. * @return
  180. */
  181. public static Response call(HttpMethod httpMethod, String url, Map<String, String> headers,
  182. Map<String, String> params) {
  183. LOG.info("[okhttp3] new call: " + httpMethod + " " + url);
  184. LOG.info("[okhttp3] headers: " + JsonUtil.toJson(headers));
  185. LOG.info("[okhttp3] params: " + JsonUtil.toJson(params));
  186. Builder builder = null;
  187. if (httpMethod.equals(HttpMethod.GET)) {
  188. url = UrlUtil.joinParams(url, params);
  189. builder = new Request.Builder().url(url).get();
  190. } else {
  191. okhttp3.FormBody.Builder formBody = new FormBody.Builder();
  192. if (null != params && 0 != params.size()) {
  193. for (Entry<String, String> entry : params.entrySet()) {
  194. formBody.add(entry.getKey(), entry.getValue());
  195. }
  196. }
  197. if (httpMethod.equals(HttpMethod.POST)) {
  198. builder = new Request.Builder().url(url).post(formBody.build());
  199. } else if (httpMethod.equals(HttpMethod.PUT)) {
  200. builder = new Request.Builder().url(url).put(formBody.build());
  201. } else if (httpMethod.equals(HttpMethod.DELETE)) {
  202. builder = new Request.Builder().url(url).delete(formBody.build());
  203. }
  204. }
  205. if (null != headers && 0 != headers.size()) {
  206. for (Entry<String, String> entry : headers.entrySet()) {
  207. builder.addHeader(entry.getKey(), entry.getValue());
  208. }
  209. }
  210. Request request = builder.build();
  211. Response response = null;
  212. try {
  213. response = okHttpClient.newCall(request).execute();
  214. return response;
  215. } catch (IOException e) {
  216. throw new RuntimeException(e);
  217. }
  218. }
  219. /**
  220. * 发送请求 (包含文件表单)
  221. *
  222. * @author WANGWEI
  223. * @param httpMethod
  224. * @param url
  225. * @param headers
  226. * @param params
  227. * @param formFilePartList
  228. * @return
  229. */
  230. public static Response call(HttpMethod httpMethod, String url, Map<String, String> headers,
  231. Map<String, String> params, List<FormFilePart> formFilePartList) {
  232. LOG.info("[okhttp3] new call: " + httpMethod + " " + url);
  233. LOG.info("[okhttp3] headers: " + JsonUtil.toJson(headers));
  234. LOG.info("[okhttp3] params: " + JsonUtil.toJson(params));
  235. okhttp3.MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()
  236. .setType(MultipartBody.ALTERNATIVE);
  237. if (null != params) {
  238. for (Entry<String, String> entry : params.entrySet()) {
  239. multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
  240. }
  241. }
  242. if (CollectionUtils.isNotEmpty(formFilePartList)) {
  243. MediaType type = MediaType.parse("application/octet-stream");
  244. for (FormFilePart part : formFilePartList) {
  245. RequestBody fileBody = RequestBody.create(type, part.getFile());
  246. multipartBodyBuilder.addFormDataPart(part.getParamName(), part.getFilename(),
  247. fileBody);
  248. }
  249. }
  250. Builder builder = new Request.Builder().url(url).post(multipartBodyBuilder.build());
  251. if (null != headers && 0 != headers.size()) {
  252. for (Entry<String, String> entry : headers.entrySet()) {
  253. builder.addHeader(entry.getKey(), entry.getValue());
  254. }
  255. }
  256. Request request = builder.build();
  257. Response response = null;
  258. try {
  259. response = okHttpClient.newCall(request).execute();
  260. return response;
  261. } catch (IOException e) {
  262. throw new RuntimeException(e);
  263. }
  264. }
  265. }