How to Add Real‑Time Alert Notifications for API Test Failures in Java

This article explains how to detect server‑induced empty JSON responses during API automation, integrate the free AlertOver service for instant failure alerts, and provides complete Java code for a robust getHttpResponse method and an AlertOver utility class to send system, function, business, and reminder messages.

FunTester
FunTester
FunTester
How to Add Real‑Time Alert Notifications for API Test Failures in Java

When performing interface automation, unstable servers can cause the JSON object of the response entity to be empty, which makes debugging difficult. To surface such failures immediately, the author added a notification mechanism using the free AlertOver service (later extended with WeChat alerts) so that server exceptions are clearly reported.

The core method getHttpResponse(HttpRequestBase request) wraps an Apache HttpClient call, optionally logs request and response headers, measures execution time, extracts status, cookies, and content, builds a JSONObject with the parsed data, checks the response via a custom iBase validator, and triggers an AlertOver message when the response is invalid. It also records test metrics (data size, elapsed time, status, etc.) into a MySQL table and handles exceptions by sending a generic "interface request failed" alert. Finally, it cleans up header flags and maintains a bounded request queue.

public static JSONObject getHttpResponse(HttpRequestBase request) {
    if (!isRightRequest(request)) return new JSONObject();
    beforeRequest(request);
    JSONObject res = new JSONObject();
    RequestInfo requestInfo = new RequestInfo(request);
    if (HEADER_KEY) output("===========request header===========", Arrays.asList(request.getAllHeaders()));
    long start = Time.getTimeStamp();
    try (CloseableHttpResponse response = ClientManage.httpsClient.execute(request)) {
        long end = Time.getTimeStamp();
        long elapsed_time = end - start;
        if (HEADER_KEY) output("===========response header===========", Arrays.asList(response.getAllHeaders()));
        int status = getStatus(response, res);
        JSONObject setCookies = afterResponse(response);
        String content = getContent(response);
        int data_size = content.length();
        res.putAll(getJsonResponse(content, setCookies));
        int code = iBase == null ? -2 : iBase.checkCode(res, requestInfo);
        if (!iBase.isRight(res))
            new AlertOver("响应状态码错误:" + status, "状态码错误:" + status, requestInfo.getUrl(), requestInfo).sendSystemMessage();
        MySqlTest.saveApiTestDate(requestInfo, data_size, elapsed_time, status, getMark(), code, LOCAL_IP, COMPUTER_USER_NAME);
    } catch (Exception e) {
        logger.warn("获取请求相应失败!", e);
        if (!SysInit.isBlack(requestInfo.getHost()))
            new AlertOver("接口请求失败", requestInfo.toString(), requestInfo.getUrl(), requestInfo).sendSystemMessage();
    } finally {
        HEADER_KEY = false;
        if (!SysInit.isBlack(requestInfo.getHost())) {
            if (requests.size() > 9) requests.removeFirst();
            requests.add(request);
        }
    }
    return res;
}

The AlertOver class encapsulates the logic for sending different types of alerts (system, function, business, reminder, code) through the AlertOver API. It defines static identifiers for each message source, provides overloaded constructors for various use cases, and implements helper methods such as sendSystemMessage(), sendFunctionMessage(), sendBusinessMessage(), sendRemindMessage(), and a generic sendMessage(String source) that builds a JSON payload and posts it to https://api.alertover.com/v1/alert. The class respects a blacklist of URLs, logs debug information, and records each alert in a MySQL table.

package com.fun.utils.message;

import com.fun.frame.httpclient.FanLibrary;
import com.fun.base.bean.RequestInfo;
import com.fun.base.interfaces.IMessage;
import com.fun.db.mysql.MySqlTest;
import com.fun.config.SysInit;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.HttpPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AlertOver extends FanLibrary implements IMessage {
    private static Logger logger = LoggerFactory.getLogger(AlertOver.class);
    String title;
    String content;
    String murl;
    RequestInfo requestInfo;
    private static String system = "s-7e93ec02-1308-480c-bc11-a7260c14"; //系统异常
    private static String function = "s-7e3b7ea5-b4b0-4479-a0e3-bce6c830"; //功能异常
    private static String business = "s-466a191a-cbb8-4164-b8be-9779bb88"; //业务异常
    private static String remind = "s-f49ac5bc-008b-4b11-890e-6715ef89"; //提醒推送
    private static String code = "s-490d0fc6-35cc-4430-9f87-09cdeb05"; //程序异常
    private static final String testGroup = "g-4eefc0ad-19af-4b1c-9d0b-ef87be15";

    public AlertOver() {
        this("test title", "test content!");
    }

    public AlertOver(String title, String content) {
        this.title = title;
        this.content = content + LINE + "发送源:" + COMPUTER_USER_NAME;
    }

    public AlertOver(String title, String content, String url) {
        this(title, content);
        this.murl = url;
    }

    public AlertOver(String title, String content, String url, RequestInfo requestInfo) {
        this(title, content);
        this.murl = url;
        this.requestInfo = requestInfo;
    }

    /** 发送系统异常 */
    public void sendSystemMessage() {
        if (SysInit.isBlack(murl)) return;
        sendMessage(system);
        MySqlTest.saveAlertOverMessage(requestInfo, "system", title, LOCAL_IP, COMPUTER_USER_NAME);
        logger.info("发送系统错误提醒,title:{},ip:{},computer:{}", title, LOCAL_IP, COMPUTER_USER_NAME);
    }

    /** 发送功能异常 */
    public void sendFunctionMessage() { sendMessage(function); }
    /** 发送业务异常 */
    public void sendBusinessMessage() { sendMessage(business); }
    /** 发送程序异常 */
    public void sendCodeMessage() { sendMessage(code); }
    /** 提醒推送 */
    public void sendRemindMessage() { sendMessage(remind); }

    /** 发送消息 */
    public void sendMessage(String source) {
        if (SysInit.isBlack(murl)) return;
        String url = "https://api.alertover.com/v1/alert";
        String receiver = testGroup; //测试组ID
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("frame", source);
        jsonObject.put("receiver", receiver);
        jsonObject.put("content", content);
        jsonObject.put("title", title);
        jsonObject.put("url", murl);
        jsonObject.put("sound", "pianobar");
        logger.debug("消息详情:{}", jsonObject.toString());
        HttpPost httpPost = getHttpPost(url, jsonObject);
        // 取消发送
        getHttpResponse(httpPost);
    }
}

By integrating these snippets into an API testing framework, developers can automatically receive clear, categorized alerts whenever a request fails or returns an unexpected status, greatly simplifying troubleshooting of unstable test environments.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendmonitoringAPI testingalert notification
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.