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 |

相关推荐
thinktik2 小时前
AWS EKS 计算资源自动扩缩之Fargate[AWS 海外区]
后端·kubernetes·aws
Pota-to成长日记2 小时前
代码解析:基于时间轴(Timeline)的博客分页查询功能
java
塔能物联运维2 小时前
物联网设备运维中的自动化合规性检查与策略执行机制
java·运维·物联网·struts·自动化
不爱编程的小九九2 小时前
小九源码-springboot099-基于Springboot的本科实践教学管理系统
java·spring boot·后端
lang201509282 小时前
Spring Boot集成Spring Integration全解析
spring boot·后端·spring
雨夜之寂2 小时前
第一章-第二节-Cursor IDE与MCP集成.md
java·后端·架构
即将头秃的程序媛3 小时前
Sa-Token
java
大G的笔记本3 小时前
Spring IOC和AOP
java·后端·spring
武子康3 小时前
Java-155 MongoDB Spring Boot 连接实战 | Template vs Repository(含索引与常见坑)
java·数据库·spring boot·后端·mongodb·系统架构·nosql
武子康3 小时前
Java-157 MongoDB 存储引擎 WiredTiger vs InMemory:何时用、怎么配、如何验证 mongod.conf
java·数据库·sql·mongodb·性能优化·系统架构·nosql