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 |

相关推荐
武子康3 分钟前
大数据-86 Spark+Scala实现WordCount:大数据学习的入门实践
大数据·后端·spark
浮游本尊4 分钟前
Java学习第18天 - Kafka消息队列与流式处理
java
wdfk_prog5 分钟前
[Linux]学习笔记系列 -- mm/slub.c SLUB内存分配器(The SLUB Allocator) 现代内核对象缓存的核心
java·linux·运维·c语言·笔记·学习·缓存
tonydf11 分钟前
MinIO祭了,RustFS来了!
后端
卓伊凡22 分钟前
苹果开发中什么是Storyboard?object-c 和swiftui 以及Storyboard到底有什么关系以及逻辑?优雅草卓伊凡
前端·后端
华仔啊27 分钟前
前后端为个下拉框又吵起来了?一招优雅的 Java 枚举解法,让团队和谐开发!
java·后端
Charlo29 分钟前
是什么让一个AI系统成为智能体(Agent)?
前端·后端
哈基米喜欢哈哈哈33 分钟前
MongoDB入门
数据库·后端·mongodb
石小石Orz34 分钟前
来自面试官给我的建议,我备受启发
前端·后端·面试
珹洺36 分钟前
Java-Spring入门指南(二)利用IDEA手把手教你如何创建第一个Spring系统
java·spring·intellij-idea