OkHttpUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package com.fdkankan.common.util;
  2. import cn.hutool.core.collection.CollectionUtil;
  3. import cn.hutool.http.HttpUtil;
  4. import lombok.extern.slf4j.Slf4j;
  5. import okhttp3.*;
  6. import org.apache.commons.lang3.ObjectUtils;
  7. import java.io.IOException;
  8. import java.util.Iterator;
  9. import java.util.Map;
  10. import java.util.Set;
  11. import java.util.concurrent.TimeUnit;
  12. import java.util.function.Consumer;
  13. //import org.springframework.http.HttpMethod;
  14. /**
  15. * @author axin
  16. * @since 2019-08-14
  17. */
  18. @Slf4j
  19. public class OkHttpUtils {
  20. // private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);
  21. private static final String HTTP_JSON = "application/json; charset=utf-8";
  22. private static final String HTTP_FORM = "application/x-www-form-urlencoded; charset=utf-8";
  23. //MEDIA_TYPE_TEXT post请求不是application/x-www-form-urlencoded的,全部直接返回,不作处理,即不会解析表单数据来放到request parameter map中。所以通过request.getParameter(name)是获取不到的。只能使用最原始的方式,读取输入流来获取。
  24. private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
  25. private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
  26. .connectTimeout(120, TimeUnit.SECONDS)
  27. .readTimeout(120, TimeUnit.SECONDS)
  28. .writeTimeout(120, TimeUnit.SECONDS)
  29. .build();
  30. /**
  31. * get请求
  32. * 对于小文档,响应体上的string()方法非常方便和高效。
  33. * 但是,如果响应主体很大(大于1 MB),则应避免string(),
  34. * 因为它会将整个文档加载到内存中。在这种情况下,将主体处理为流。
  35. *
  36. * @param url
  37. * @return
  38. */
  39. public static String httpGet(String url) {
  40. if (url == null || "".equals(url)) {
  41. log.error("url为null!");
  42. return "";
  43. }
  44. Request.Builder builder = new Request.Builder();
  45. Request request = builder.get().url(url).build();
  46. try {
  47. Response response = okHttpClient.newCall(request).execute();
  48. if (response.code() == 200) {
  49. log.info("http GET 请求成功; [url={}]", url);
  50. return response.body().string();
  51. } else {
  52. log.warn("Http GET 请求失败; [errorCode = {} , url={}]", response.code(), url);
  53. log.info(response.body().string());
  54. }
  55. } catch (IOException e) {
  56. throw new RuntimeException("同步http GET 请求失败,url:" + url, e);
  57. }
  58. return null;
  59. }
  60. public static String httpGet(String url, Map<String, String> headers) {
  61. if (ObjectUtils.isEmpty(headers)) {
  62. return httpGet(url);
  63. }
  64. Request.Builder builder = new Request.Builder();
  65. headers.forEach((String key, String value) -> builder.header(key, value));
  66. Request request = builder.get().url(url).build();
  67. try {
  68. Response response = okHttpClient.newCall(request).execute();
  69. if (response.code() == 200) {
  70. log.info("http GET 请求成功; [url={}]", url);
  71. return response.body().string();
  72. } else {
  73. log.warn("Http GET 请求失败; [errorxxCode = {} , url={}]", response.code(), url);
  74. }
  75. } catch (IOException e) {
  76. throw new RuntimeException("同步http GET 请求失败,url:" + url, e);
  77. }
  78. return null;
  79. }
  80. /**
  81. * @author xiaobu
  82. * @date 2019/3/4 15:58
  83. * @param url , params]
  84. * @return java.lang.String
  85. * @descprition post方式请求
  86. * @version 1.0
  87. */
  88. public static String sendByPostMap(String url, Map<String, String> params) {
  89. String result;
  90. OkHttpClient client = new OkHttpClient();
  91. StringBuilder content = new StringBuilder();
  92. Set<Map.Entry<String, String>> entrys = params.entrySet();
  93. Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
  94. while (iterator.hasNext()) {
  95. Map.Entry<String, String> entry = iterator.next();
  96. content.append(entry.getKey()).append("=").append(entry.getValue());
  97. if (iterator.hasNext()) {
  98. content.append("&");
  99. }
  100. }
  101. RequestBody requestBody = RequestBody.create(MEDIA_TYPE_TEXT, content.toString());
  102. Request request = new Request.Builder().url(url).post(requestBody).build();
  103. Response response = null;
  104. try {
  105. response = client.newCall(request).execute();
  106. assert response.body() != null;
  107. result = response.body().string();
  108. System.out.println("result = " + result);
  109. return result;
  110. } catch (IOException e) {
  111. e.printStackTrace();
  112. }
  113. return null;
  114. }
  115. /**
  116. * 同步 POST调用 无Header
  117. *
  118. * @param url
  119. * @param json
  120. * @return
  121. */
  122. public static String httpPostJson(String url, String json) {
  123. if (url == null || "".equals(url)) {
  124. log.error("url为null!");
  125. return "";
  126. }
  127. MediaType JSON = MediaType.parse(HTTP_JSON);
  128. RequestBody body = RequestBody.create(JSON, json);
  129. Request.Builder requestBuilder = new Request.Builder().url(url);
  130. Request request = requestBuilder.post(body).build();
  131. try {
  132. Response response = okHttpClient.newCall(request).execute();
  133. if (response.code() == 200) {
  134. log.info("http Post 请求成功; [url={}, requestContent={}]", url, json);
  135. return response.body().string();
  136. } else {
  137. log.warn("Http POST 请求失败; [ errorCode = {}, url={}, param={}]", response.code(), url, json);
  138. }
  139. } catch (IOException e) {
  140. throw new RuntimeException("同步http请求失败,url:" + url, e);
  141. }
  142. return null;
  143. }
  144. /**
  145. * 同步 POST调用 有Header
  146. *
  147. * @param url
  148. * @param headers
  149. * @param json
  150. * @return
  151. */
  152. public static String httpPostJson(String url, Map<String, String> headers, String json) {
  153. if (CollectionUtil.isEmpty(headers)) {
  154. httpPostJson(url, json);
  155. }
  156. MediaType JSON = MediaType.parse(HTTP_JSON);
  157. RequestBody body = RequestBody.create(JSON, json);
  158. Request.Builder requestBuilder = new Request.Builder().url(url);
  159. headers.forEach((k, v) -> requestBuilder.addHeader(k, v));
  160. Request request = requestBuilder.post(body).build();
  161. try {
  162. Response response = okHttpClient.newCall(request).execute();
  163. if (response.code() == 200) {
  164. log.info("http Post 请求成功; [url={}, requestContent={}]", url, json);
  165. return response.body().string();
  166. } else {
  167. log.warn("Http POST 请求失败; [ errorCode = {}, url={}, param={}]", response.code(), url, json);
  168. }
  169. } catch (IOException e) {
  170. throw new RuntimeException("同步http请求失败,url:" + url, e);
  171. }
  172. return null;
  173. }
  174. /**
  175. * 提交表单
  176. * @param url
  177. * @param content
  178. * @param headers
  179. * @return
  180. */
  181. public static String postDataByForm(String url, String content, Map<String, String> headers) {
  182. MediaType JSON = MediaType.parse(HTTP_FORM);
  183. RequestBody body = RequestBody.create(JSON, content);
  184. Request.Builder requestBuilder = new Request.Builder().url(url);
  185. if (headers != null && headers.size() > 0) {
  186. headers.forEach((k, v) -> requestBuilder.addHeader(k, v));
  187. }
  188. Request request = requestBuilder
  189. .post(body)
  190. .build();
  191. Response response = null;
  192. try {
  193. response = okHttpClient.newCall(request).execute();
  194. if (response.code() == 200) {
  195. log.info("postDataByForm; [postUrl={}, requestContent={}, responseCode={}]", url, content, response.code());
  196. return response.body().string();
  197. } else {
  198. log.warn("Http Post Form请求失败,[url={}, param={}]", url, content);
  199. }
  200. } catch (IOException e) {
  201. log.error("Http Post Form请求失败,[url={}, param={}]", url, content, e);
  202. throw new RuntimeException("Http Post Form请求失败,url:" + url);
  203. }
  204. return null;
  205. }
  206. /**
  207. * 异步Http调用参考模板:Get、Post、Put
  208. * 需要异步调用的接口一般情况下你需要定制一个专门的Http方法
  209. *
  210. * @param httpMethod
  211. * @param url
  212. * @param content
  213. * @return
  214. */
  215. // @Deprecated
  216. // public static Future<Boolean> asyncHttpByJson(HttpMethod httpMethod, String url, Map<String, String> headers, String content) {
  217. // MediaType JSON = MediaType.parse(HTTP_JSON);
  218. // RequestBody body = RequestBody.create(JSON, content);
  219. //
  220. // Request.Builder requestBuilder = new Request.Builder()
  221. // .url(url);
  222. //
  223. // if (!CollectionUtils.isEmpty(headers)) {
  224. // headers.forEach((key, value) -> requestBuilder.header(key, value));
  225. // }
  226. //
  227. // switch (httpMethod) {
  228. // case GET:
  229. // requestBuilder.get();
  230. // break;
  231. // case POST:
  232. // requestBuilder.post(body);
  233. // break;
  234. // default:
  235. // }
  236. //
  237. // Request request = requestBuilder.build();
  238. // Call call = okHttpClient.newCall(request);
  239. // call.enqueue(new Callback() {
  240. // @Override
  241. // public void onFailure(Call call, IOException e) {
  242. // log.error("异步http {} 请求失败,[url={}, param={}]", httpMethod.name(), url, content);
  243. // throw new RuntimeException("异步http请求失败,url:" + url);
  244. // }
  245. //
  246. // @Override
  247. // public void onResponse(Call call, final Response response) throws IOException {
  248. // if (response.code() == 200) {
  249. // System.out.println("需要加入异步回调操作");
  250. // } else {
  251. // log.error("异步http {} 请求失败,错误码为{},请求参数为[url={}, param={}]", httpMethod.name(), response.code(), url, content);
  252. // }
  253. // }
  254. // });
  255. // return new AsyncResult(true);
  256. // }
  257. /**
  258. * lambda表达式异步调用http模板,不建议使用
  259. *
  260. * @param request
  261. * @param failure
  262. * @param respConsumer
  263. */
  264. public static void asyncCall(Request request, Consumer<Exception> failure, Consumer<Response> respConsumer) {
  265. okHttpClient.newCall(request).enqueue(new Callback() {
  266. @Override
  267. public void onFailure(Call call, IOException e) {
  268. failure.accept(e);
  269. }
  270. @Override
  271. public void onResponse(Call call, Response response) throws IOException {
  272. respConsumer.accept(response);
  273. }
  274. });
  275. }
  276. public static long downloadFile(String url, String dest,int retryTimes){
  277. for (int i = 0; i <= retryTimes; i++) {
  278. try {
  279. return HttpUtil.downloadFile(url, dest);
  280. } catch (Exception e) {
  281. e.printStackTrace();
  282. log.error(String.format("文件第%d次下载失败", i + 1), e);
  283. try {
  284. Thread.sleep(3000);
  285. } catch (InterruptedException interruptedException) {
  286. interruptedException.printStackTrace();
  287. }
  288. }
  289. }
  290. return 0L;
  291. }
  292. }