java工具类OKHTTP

Okhttp

1.首先需要导入OkHttp的maven相关坐标。

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.1</version>
 </dependency>

2.编写所需要的类,这个是枚举类,通过返回状态码可以看出,请求是否发送成功。

import com.alibaba.druid.wall.violation.ErrorCode;

/**
 * 异常编码 0成功、-1熔断、 -2 标准参数校验不通过 -3会话超时
 * 前两位:服务标识
 * 中间两位:模块标识
 * 后两位:异常标识
 */
public enum CommonErrorCode implements ErrorCode {
	
	公用异常编码 //

	SUCCESS(0, "成功"),
	FUSE(-1, "网关调用熔断"),

	/**
	 * 传入参数与接口不匹配
	 */
	E_100101(100101,"传入参数与接口不匹配"),
	/**
	 * 验证码错误
	 */
	E_100102(100102,"验证码错误"),
	/**
	 * 验证码为空
	 */
	E_100103(100103,"验证码为空"),
	/**
     * 查询结果为空
     */
    E_100104(100104,"查询结果为空"),
    /**
     * ID格式不正确或超出Long存储范围
     */
    E_100105(100105,"ID格式不正确或超出Long存储范围"),

	E_100106(100106,"请求失败"),

    E_999990(999990,"调用微服务-交易中心 被熔断"),
    E_999991(999991,"调用微服务-授权服务 被熔断"),
    E_999992(999992,"调用微服务-用户服务 被熔断"),
    E_999993(999993,"调用微服务-资源服务 被熔断"),
    E_999994(999994,"调用微服务-同步服务 被熔断"),
	E_999995(999995,"调用微服务-统一账户服务 被熔断"),
	E_999996(999996,"调用微服务-存管代理服务 被熔断"),
	/**
	 * 调用微服务-还款服务 被熔断
	 */
	E_999997(999997,"调用微服务-还款服务 被熔断"),
	CUSTOM(999998,"自定义异常"),
	/**
	 * 未知错误
	 */
	UNKOWN(999999,"未知错误");
	

	private int code;
	private String desc;
		
	public int getCode() {
		return code;
	}

	public String getDesc() {
		return desc;
	}

	private CommonErrorCode(int code, String desc) {
		this.code = code;
		this.desc = desc;
	}


	public static CommonErrorCode setErrorCode(int code) {
       for (CommonErrorCode errorCode : CommonErrorCode.values()) {
           if (errorCode.getCode()==code) {
               return errorCode;
           }
       }
	       return null;
	}
}

3.封装类,发送请求时,把数据封装成一个实体。通过get方法获取相应的数据。

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@JsonInclude(Include.NON_NULL)
@ApiModel(value = "RestResponse<T>", description = "响应通用参数包装")
public class RestResponse<T> {

	@ApiModelProperty("响应错误编码,0为正常")
	private int code;
	
	@ApiModelProperty("响应错误信息")
	private String msg;
	
	@ApiModelProperty("响应内容")
	private T result;
	private JSONObject jsonObject;

	public static <T> RestResponse<T> success() {
		return new RestResponse<T>();
	}

	public static <T> RestResponse<T> success(T result) {
		RestResponse<T> response = new RestResponse<T>();
		response.setResult(result);
		return response;
	}

	public static <T> RestResponse<T> validfail(String msg) {
		RestResponse<T> response = new RestResponse<T>();
		response.setCode(-2);
		response.setMsg(msg);
		return response;
	}

	public RestResponse() {
		this(0, "");
	}

	public RestResponse(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	public T getResult() {
		return result;
	}

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

	@JsonIgnore
	public Boolean isSuccessful() {
		return this.code == 0;
	}

	@Override
	public String toString() {
		return "RestResponse{" +
				"code=" + code +
				", msg='" + msg + '\'' +
				", result=" + result +
				", jsonObject=" + jsonObject +
				'}';
	}
}

4.Okhttp工具类,这个工具类只支持post请求,无法封装json对象,如果需要请到本人的其他文章查看。

import me.zhengjie.mybatis.domain.CommonErrorCode;
import me.zhengjie.mybatis.domain.RestResponse;
import com.alibaba.fastjson.JSON;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * <P>
 * okHttp3请求工具类
 * </p>
 */
public class OkHttpUtil {

	private static OkHttpClient okHttpClient = new OkHttpClient().newBuilder().retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS).build();

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

	/**
	 * 发送post请求
	 * @param url
	 * @param json
	 * @return
	 */
	public static RestResponse post(String url, String json) {
		okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON_TYPE, json);
		Request request = new Request.Builder().url(url).post(body).build();
		try (Response response = okHttpClient.newCall(request).execute()) {
			okhttp3.ResponseBody responseBody = response.body();
			if (responseBody != null) {
				return JSON.parseObject(responseBody.string(), RestResponse.class);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return RestResponse.validfail(CommonErrorCode.E_100106.getDesc());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值