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

发布于:2025-07-18 ⋅ 阅读:(16) ⋅ 点赞:(0)

✅ 背景与需求

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

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


✅ 项目结构参考

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

// 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

// 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 配置)

// 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


网站公告

今日签到

点亮在社区的每一天
去签到