JAVA okhttp 工具类

工具类:OkHttpClients 

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * Created by zhonglin on 2018/7/25.
 */
public class OkHttpClients {

  /**
   * get请求
   */
  public static <T> OkhttpResult<T> get(OkHttpParam restParam, Class<T> tClass) throws Exception {
    String url = restParam.getApiUrl();

    if (restParam.getApiPath() != null) {
      url = url+restParam.getApiPath();
    }
    Request request = new Request.Builder()
        .url(url)
        .get()
        .build();
    return exec(restParam, request, tClass);
  }

  /**
   * POST请求json数据
   */
  public static <T> OkhttpResult<T> post(OkHttpParam restParam, String reqJsonData, Class<T> tClass) throws Exception {
    String url = restParam.getApiUrl();

    if (restParam.getApiPath() != null) {
      url = url+restParam.getApiPath();
    }
    RequestBody body = RequestBody.create(restParam.getMediaType(), reqJsonData);

    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    return exec(restParam, request, tClass);
  }

  /**
   * POST请求map数据
   */
  public static <T> OkhttpResult<T> post(OkHttpParam restParam, Map<String, String> parms, Class<T> tClass) throws Exception {
    String url = restParam.getApiUrl();

    if (restParam.getApiPath() != null) {
      url = url+restParam.getApiPath();
    }
    FormBody.Builder builder = new FormBody.Builder();

    if (parms != null) {
      for (Map.Entry<String, String> entry : parms.entrySet()) {
        builder.add(entry.getKey(), entry.getValue());
      }
    }

    FormBody body = builder.build();

    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    return exec(restParam, request, tClass);
  }

  /**
   * 返回值封装成对象
   */
  private static <T> OkhttpResult<T> exec(
      OkHttpParam restParam,
      Request request,
      Class<T> tClass) throws Exception {

    OkhttpResult clientResult = exec(restParam, request);
    String result = clientResult.getResult();
    int status = clientResult.getStatus();

    T t = null;
    if (status == 200) {
      if (result != null && "".equalsIgnoreCase(result)) {
        t = JSON.parseObject(result, tClass);
      }
    } else {
      try {
        result = JSON.parseObject(result, String.class);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    return new OkhttpResult<>(clientResult.getStatus(), result, t);
  }

  /**
   * 执行方法
   */
  private static OkhttpResult exec(
      OkHttpParam restParam,
      Request request) throws Exception {

    OkhttpResult result = null;

    okhttp3.OkHttpClient client = null;
    ResponseBody responseBody = null;
    try {
      client = new okhttp3.OkHttpClient();

      client.newBuilder()
          .connectTimeout(restParam.getConnectTimeout(), TimeUnit.MILLISECONDS)
          .readTimeout(restParam.getReadTimeout(), TimeUnit.MILLISECONDS)
          .writeTimeout(restParam.getWriteTimeout(), TimeUnit.MILLISECONDS);

      Response response = client.newCall(request).execute();

      if (response.isSuccessful()) {
        responseBody = response.body();
        if (responseBody != null) {
          String responseString = responseBody.string();

          result = new OkhttpResult<>(response.code(), responseString, null);
        }
      } else {
        throw new Exception(response.message());
      }
    } catch (Exception ex) {
      throw new Exception(ex.getMessage());
    } finally {
      if (responseBody != null) {
        responseBody.close();
      }
      if (client != null) {
        client.dispatcher().executorService().shutdown();   //清除并关闭线程池
        client.connectionPool().evictAll();                 //清除并关闭连接池
        try {
          if (client.cache() != null) {
            client.cache().close();                         //清除cache
          }
        } catch (IOException e) {
          throw new Exception(e.getMessage());
        }
      }
    }
    return result;
  }

}

请求对象:OkHttpParam 

import okhttp3.MediaType;

/**
 * Created by zhonglin on 2018/7/25.
 */
public class OkHttpParam {

  public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

  /**
   * 接口URL
   */
  private String apiUrl;

  /**
   * 接口路径
   */
  private String apiPath;

  /**
   * 读取超时时间
   */
  private int readTimeout = 30 * 1000;

  /**
   * 写入超时时间
   */
  private int writeTimeout = 30 * 1000;

  /**
   * 连接超时时间
   */
  private int connectTimeout = 2 * 1000;

  /**
   * 编码类型
   */
  private MediaType mediaType = MEDIA_TYPE_JSON;

  public String getApiUrl() {
    return apiUrl;
  }

  public void setApiUrl(String apiUrl) {
    this.apiUrl = apiUrl;
  }

  public String getApiPath() {
    return apiPath;
  }

  public void setApiPath(String apiPath) {
    this.apiPath = apiPath;
  }

  public int getReadTimeout() {
    return readTimeout;
  }

  public void setReadTimeout(int readTimeout) {
    this.readTimeout = readTimeout;
  }

  public int getWriteTimeout() {
    return writeTimeout;
  }

  public void setWriteTimeout(int writeTimeout) {
    this.writeTimeout = writeTimeout;
  }

  public int getConnectTimeout() {
    return connectTimeout;
  }

  public void setConnectTimeout(int connectTimeout) {
    this.connectTimeout = connectTimeout;
  }

  public MediaType getMediaType() {
    return mediaType;
  }

  public void setMediaType(MediaType mediaType) {
    this.mediaType = mediaType;
  }
}

响应对象:OkhttpResult

public class OkhttpResult<T> {

  private int status;
  private String     result;
  private T          resultObject;

  public OkhttpResult() {
  }

  public OkhttpResult(int status, String result, T resultObject) {
    this.status = status;
    this.result = result;
    this.resultObject = resultObject;
  }

  public int getStatus() {
    return status;
  }

  public void setStatus(int status) {
    this.status = status;
  }

  public String getResult() {
    return result;
  }

  public void setResult(String result) {
    this.result = result;
  }

  public T getResultObject() {
    return resultObject;
  }

  public void setResultObject(T resultObject) {
    this.resultObject = resultObject;
  }

测试方法:

public class OkHttpClientsTest {

  public static void main(String[] args) throws Exception {

    OkHttpParam param = new OkHttpParam();
    param.setApiUrl("http://127.0.0.1:7015/api");
    param.setApiPath("/batch/btb_batchinfo");

    Map<String, String> map = new HashMap<>();

    String a = "{\"body\":{\"batch_list\":[{\"batch_code\":\"3934630\",\"box_list\":[{\"box_code\":\"3934630201807*07\",\"qty\":1,\"sku\":\"6508827101\"},{\"box_code\":\"3934630201807*07\",\"qty\":1,\"sku\":\"S970000901\"},{\"box_code\":\"3934630201807*08\",\"qty\":1,\"sku\":\"6508827101\"}],\"from_warehouse\":\"218\",\"to_warehouse\":\"1321\"}]},\"header\":{\"message_id\":\"2018080114182503500949856842\",\"sign\":\"d21caa4cad66de334fafdcfa7b345bff\",\"time_stamp\":\"1533104305350\",\"transaction_type\":\"btb_batchinfo\"}}";

    map.put("msg", JSON.toJSONString(a));

    OkhttpResult<String> result = OkHttpClients.post(param, map, String.class);

    System.out.println("result:"+JSON.toJSONString(result));


  }

}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
下面是一个简单的 Java OkHttp3 工具类的示例代码: ```java import okhttp3.*; import java.io.IOException; import java.util.Map; public class OkHttpUtil { private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final OkHttpClient client = new OkHttpClient(); /** * GET 请求 * * @param url 请求地址 * @return 响应结果字符串 * @throws IOException 请求失败抛出异常 */ public static String get(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } /** * POST 请求 * * @param url 请求地址 * @param params 请求参数 * @return 响应结果字符串 * @throws IOException 请求失败抛出异常 */ public static String post(String url, Map<String, String> params) throws IOException { FormBody.Builder formBuilder = new FormBody.Builder(); for (Map.Entry<String, String> entry : params.entrySet()) { formBuilder.add(entry.getKey(), entry.getValue()); } RequestBody requestBody = formBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } /** * POST 请求,请求体为 JSON 格式 * * @param url 请求地址 * @param json 请求体 JSON 字符串 * @return 响应结果字符串 * @throws IOException 请求失败抛出异常 */ public static String postJson(String url, String json) throws IOException { RequestBody requestBody = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } } ``` 使用示例: ```java public class Main { public static void main(String[] args) throws IOException { // GET 请求 System.out.println(OkHttpUtil.get("https://www.baidu.com")); // POST 请求,表单参数 Map<String, String> params = new HashMap<>(); params.put("name", "张三"); params.put("age", "18"); System.out.println(OkHttpUtil.post("http://localhost:8080/user", params)); // POST 请求,JSON 参数 String json = "{\"name\":\"张三\",\"age\":18}"; System.out.println(OkHttpUtil.postJson("http://localhost:8080/user", json)); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时光下的旅途

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值