OkHttp 框架封装一个 HTTP 客户端,用于调用外部服务接口

✅ 背景与需求

需要基于 OkHttp 框架封装一个 HTTP 客户端,用于调用外部服务接口(如拼团回调),实现以下功能:

  • 动态传入请求地址(URL)
  • 支持 JSON 请求体
  • 实现类放在 infrastructure 层的 gateway 包下
  • 接口定义在 domain 层,实现类为 GroupBuyNotifyService

✅ 项目结构参考

java 复制代码
group-buy-market
├── group-buy-market-domain
│   └── src/main/java/cn/bugstack/domain/trade/service/settlement/notify/GroupBuyNotifyService.java
├── group-buy-market-infrastructure
│   └── src/main/java/cn/bugstack/infrastructure/gateway/GroupBuyNotifyGateway.java

✅接口设计

1. 领域层接口(定义在 domain

java 复制代码
// GroupBuyNotifyService.java
package cn.bugstack.domain.trade.service.settlement.notify;

import cn.bugstack.domain.trade.model.entity.NotifyTaskEntity;

import java.util.Map;

public interface GroupBuyNotifyService {
    String groupBuyNotify(NotifyTaskEntity notifyTaskEntity);
}

2. 基础设施层实现(定义在 infrastructure

java 复制代码
// GroupBuyNotifyGateway.java
package cn.bugstack.infrastructure.gateway;

import cn.bugstack.domain.trade.model.entity.NotifyTaskEntity;
import cn.bugstack.domain.trade.service.settlement.notify.GroupBuyNotifyService;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GroupBuyNotifyGateway implements GroupBuyNotifyService {

    private final final OkHttpClient httpClient;

    public GroupBuyNotifyGateway(OKHttpClientConfig okHttpClientConfig) {
        this.httpClient = okHttpClientConfig.getOkHttpClient();
    }

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTaskEntity) {
        String url = notifyTaskEntity.getNotifyUrl(); // 动态 URL
        String requestBody = JSON.toJSONString(notifyTaskEntity); // 请求体

        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(requestBody, MediaType.get("application/json; charset=utf-8")))
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            } else {
                return "HTTP_ERROR";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "NETWORK_ERROR";
        }
    }
}

✅ 配置类(OkHttpClient 配置)

java 复制代码
// OKHttpClientConfig.java
package cn.bugstack.infrastructure.config;

import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
public class OKHttpClientConfig {

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(Duration.ofSeconds(10))
                .readTimeout(Duration.ofSeconds(30))
                .writeTimeout(Duration.ofSeconds(30))
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        return okHttpClient();
    }
}

✅ 总结功能

|----------|----------------------------------------|
| 功能 | 实现方式 |
| 动态 URL | 从 notifyTaskEntity.getNotifyUrl() 获取 |
| 请求体 | 使用 FastJSON 序列化 NotifyTaskEntity |
| HTTP 客户端 | 使用 OkHttpClient 发送 POST 请求 |
| 异常处理 | 捕获 IO 异常并返回错误码 |
| 分层结构 | 接口在 domain,实现类在 infrastructure/gateway |

相关推荐
wangmengxxw3 分钟前
Swagger技术
java·swagger
大橙子打游戏3 分钟前
mp4文件在CDN上无法在网页播放的问题
后端
全干engineer32 分钟前
idea拉取github代码 -TLS connect error 异常问题
java·github·intellij-idea
10岁的博客43 分钟前
二维差分算法高效解靶场问题
java·服务器·算法
百***93501 小时前
Tomcat报404问题解决方案大全(包括tomcat可以正常运行但是报404)
java·tomcat
qq_281317471 小时前
kubernetes(k8s)-pod生命周期
java·容器·kubernetes
IT界的奇葩1 小时前
代码规范 spring-javaformat使用
java·spring·代码规范
披着羊皮不是狼1 小时前
多用户跨学科交流系统(4)参数校验+分页搜索全流程的实现
java·spring boot
小池先生2 小时前
Gradle vs Maven 详细对比
java·maven
q***23922 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring