POM

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>4.0.1</version>
  5. </dependency>

工具类

  1. import okhttp3.Call;
  2. import okhttp3.Callback;
  3. import okhttp3.MediaType;
  4. import okhttp3.OkHttpClient;
  5. import okhttp3.Request;
  6. import okhttp3.RequestBody;
  7. import okhttp3.Response;
  8. import java.io.IOException;
  9. import java.util.Iterator;
  10. import java.util.Map;
  11. import java.util.concurrent.TimeUnit;
  12. /**
  13. * OKHttp3
  14. * <p>
  15. * Description:
  16. * </p>
  17. *
  18. * @author Lusifer
  19. * @version v1.0.0
  20. * @date 2019-07-29 14:05:08
  21. * @see com.funtl.myshop.plus.commons.utils
  22. */
  23. public class OkHttpClientUtil {
  24. private static final int READ_TIMEOUT = 100;
  25. private static final int CONNECT_TIMEOUT = 60;
  26. private static final int WRITE_TIMEOUT = 60;
  27. private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  28. private static final byte[] LOCKER = new byte[0];
  29. private static OkHttpClientUtil mInstance;
  30. private OkHttpClient okHttpClient;
  31. private OkHttpClientUtil() {
  32. okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder();
  33. // 读取超时
  34. clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
  35. // 连接超时
  36. clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
  37. //写入超时
  38. clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);
  39. okHttpClient = clientBuilder.build();
  40. }
  41. /**
  42. * 单例模式获取 NetUtils
  43. *
  44. * @return {@link OkHttpClientUtil}
  45. */
  46. public static OkHttpClientUtil getInstance() {
  47. if (mInstance == null) {
  48. synchronized (LOCKER) {
  49. if (mInstance == null) {
  50. mInstance = new OkHttpClientUtil();
  51. }
  52. }
  53. }
  54. return mInstance;
  55. }
  56. /**
  57. * GET,同步方式,获取网络数据
  58. *
  59. * @param url 请求地址
  60. * @return {@link Response}
  61. */
  62. public Response getData(String url) {
  63. // 构造 Request
  64. Request.Builder builder = new Request.Builder();
  65. Request request = builder.get().url(url).build();
  66. // 将 Request 封装为 Call
  67. Call call = okHttpClient.newCall(request);
  68. // 执行 Call,得到 Response
  69. Response response = null;
  70. try {
  71. response = call.execute();
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. }
  75. return response;
  76. }
  77. /**
  78. * POST 请求,同步方式,提交数据
  79. *
  80. * @param url 请求地址
  81. * @param bodyParams 请求参数
  82. * @return {@link Response}
  83. */
  84. public Response postData(String url, Map<String, String> bodyParams) {
  85. // 构造 RequestBody
  86. RequestBody body = setRequestBody(bodyParams);
  87. // 构造 Request
  88. Request.Builder requestBuilder = new Request.Builder();
  89. Request request = requestBuilder.post(body).url(url).build();
  90. // 将 Request 封装为 Call
  91. Call call = okHttpClient.newCall(request);
  92. // 执行 Call,得到 Response
  93. Response response = null;
  94. try {
  95. response = call.execute();
  96. } catch (IOException e) {
  97. e.printStackTrace();
  98. }
  99. return response;
  100. }
  101. /**
  102. * GET 请求,异步方式,获取网络数据
  103. *
  104. * @param url 请求地址
  105. * @param myNetCall 回调函数
  106. */
  107. public void getDataAsync(String url, final MyNetCall myNetCall) {
  108. // 构造 Request
  109. Request.Builder builder = new Request.Builder();
  110. Request request = builder.get().url(url).build();
  111. // 将 Request 封装为 Call
  112. Call call = okHttpClient.newCall(request);
  113. // 执行 Call
  114. call.enqueue(new Callback() {
  115. @Override
  116. public void onFailure(Call call, IOException e) {
  117. myNetCall.failed(call, e);
  118. }
  119. @Override
  120. public void onResponse(Call call, Response response) throws IOException {
  121. myNetCall.success(call, response);
  122. }
  123. });
  124. }
  125. /**
  126. * POST 请求,异步方式,提交数据
  127. *
  128. * @param url 请求地址
  129. * @param bodyParams 请求参数
  130. * @param myNetCall 回调函数
  131. */
  132. public void postDataAsync(String url, Map<String, String> bodyParams, final MyNetCall myNetCall) {
  133. // 构造 RequestBody
  134. RequestBody body = setRequestBody(bodyParams);
  135. // 构造 Request
  136. buildRequest(url, myNetCall, body);
  137. }
  138. /**
  139. * 同步 POST 请求,使用 JSON 格式作为参数
  140. *
  141. * @param url 请求地址
  142. * @param json JSON 格式参数
  143. * @return 响应结果
  144. * @throws IOException 异常
  145. */
  146. public String postJson(String url, String json) throws IOException {
  147. RequestBody body = RequestBody.create(JSON, json);
  148. Request request = new Request.Builder()
  149. .url(url)
  150. .post(body)
  151. .build();
  152. Response response = okHttpClient.newCall(request).execute();
  153. if (response.isSuccessful()) {
  154. return response.body().string();
  155. } else {
  156. throw new IOException("Unexpected code " + response);
  157. }
  158. }
  159. /**
  160. * 异步 POST 请求,使用 JSON 格式作为参数
  161. *
  162. * @param url 请求地址
  163. * @param json JSON 格式参数
  164. * @param myNetCall 回调函数
  165. * @throws IOException 异常
  166. */
  167. public void postJsonAsync(String url, String json, final MyNetCall myNetCall) throws IOException {
  168. RequestBody body = RequestBody.create(JSON, json);
  169. // 构造 Request
  170. buildRequest(url, myNetCall, body);
  171. }
  172. /**
  173. * 构造 POST 请求参数
  174. *
  175. * @param bodyParams 请求参数
  176. * @return {@link RequestBody}
  177. */
  178. private RequestBody setRequestBody(Map<String, String> bodyParams) {
  179. RequestBody body = null;
  180. okhttp3.FormBody.Builder formEncodingBuilder = new okhttp3.FormBody.Builder();
  181. if (bodyParams != null) {
  182. Iterator<String> iterator = bodyParams.keySet().iterator();
  183. String key = "";
  184. while (iterator.hasNext()) {
  185. key = iterator.next().toString();
  186. formEncodingBuilder.add(key, bodyParams.get(key));
  187. }
  188. }
  189. body = formEncodingBuilder.build();
  190. return body;
  191. }
  192. /**
  193. * 构造 Request 发起异步请求
  194. *
  195. * @param url 请求地址
  196. * @param myNetCall 回调函数
  197. * @param body {@link RequestBody}
  198. */
  199. private void buildRequest(String url, MyNetCall myNetCall, RequestBody body) {
  200. Request.Builder requestBuilder = new Request.Builder();
  201. Request request = requestBuilder.post(body).url(url).build();
  202. // 将 Request 封装为 Call
  203. Call call = okHttpClient.newCall(request);
  204. // 执行 Call
  205. call.enqueue(new Callback() {
  206. @Override
  207. public void onFailure(Call call, IOException e) {
  208. myNetCall.failed(call, e);
  209. }
  210. @Override
  211. public void onResponse(Call call, Response response) throws IOException {
  212. myNetCall.success(call, response);
  213. }
  214. });
  215. }
  216. /**
  217. * 自定义网络回调接口
  218. */
  219. public interface MyNetCall {
  220. /**
  221. * 请求成功的回调处理
  222. *
  223. * @param call {@link Call}
  224. * @param response {@link Response}
  225. * @throws IOException 异常
  226. */
  227. void success(Call call, Response response) throws IOException;
  228. /**
  229. * 请求失败的回调处理
  230. *
  231. * @param call {@link Call}
  232. * @param e 异常
  233. */
  234. void failed(Call call, IOException e);
  235. }
  236. }