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 |

相关推荐
追逐时光者1 天前
一款使用 C# 编写专为 Windows 11 打造的文件资源管理器增强工具!
后端·.net
风象南1 天前
普通人用AI加持赚到的第一个100块
人工智能·后端
皮皮林5511 天前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河1 天前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
JavaGuide1 天前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
桦说编程1 天前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
格砸1 天前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
蝎子莱莱爱打怪1 天前
GitLab CI/CD + Docker Registry + K8s 部署完整实战指南
后端·docker·kubernetes
躺平大鹅1 天前
Java面向对象入门(类与对象,新手秒懂)
java