Okhttp通用工具类

打印 上一主题 下一主题

主题 565|帖子 565|积分 1695


  • 通用get和post哀求
  1. import cn.hutool.json.JSONUtil;
  2. import okhttp3.*;
  3. import java.io.IOException;
  4. import java.util.Map;
  5. /**
  6. * @ClassName OkHttpUtils
  7. * @description: http客户端远程调用通用工具类
  8. * @author: chenlf
  9. * @Version 1.0
  10. **/
  11. public class OkHttpUtils {
  12.     private static OkHttpClient client = new OkHttpClient();
  13.     public static String execute(String url, String method, RequestBody requestBody, Map<String, String> headers){
  14.         Request.Builder requestBuilder = new Request.Builder()
  15.                 .url(url)
  16.                 .method(method, requestBody);
  17.         if (headers != null && !headers.isEmpty()) {
  18.             for (Map.Entry<String, String> entry : headers.entrySet()) {
  19.                 requestBuilder.addHeader(entry.getKey(), entry.getValue());
  20.             }
  21.         }
  22.         try (Response response = client.newCall(requestBuilder.build()).execute()) {
  23.             if (!response.isSuccessful())
  24.                 throw new IOException("远程调用接口失败:" + response);
  25.             return response.body().string();
  26.         } catch (IOException e) {
  27.             throw new RuntimeException(e);
  28.         }
  29.     }
  30.     public static String doGet(String url){
  31.         return execute(url, "GET", null, null);
  32.     }
  33.     public static String doGet(String url, Map<String, String> headers){
  34.         return execute(url, "GET", null, headers);
  35.     }
  36.     public static String doPost(String url, String jsonBody){
  37.         RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(jsonBody));
  38.         return execute(url, "POST", body, null);
  39.     }
  40.     public static String doPost(String url, RequestBody body){
  41.         return execute(url, "POST", body, null);
  42.     }
  43.     public static String doPost(String url, String jsonBody, Map<String, String> headers){
  44.         RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSONUtil.toJsonStr(jsonBody));
  45.         return execute(url, "POST", body, headers);
  46.     }
  47.     public static String doPost(String url, RequestBody body, Map<String, String> headers){
  48.         return execute(url, "POST", body, headers);
  49.     }
  50. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

三尺非寒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表