Building an Interface Testing Project with the FunRequest Java Framework

This article guides Java developers on creating a comprehensive interface testing project using the FunRequest framework, covering reusable utilities, request/response handling, and detailed code examples for HTTP GET and POST operations, while also providing links to related tutorial videos.

FunTester
FunTester
FunTester
Building an Interface Testing Project with the FunRequest Java Framework

The video series on the FunTester interface testing framework has concluded, and readers with basic Java knowledge are now guided on building a full‑featured interface testing project that handles multiple scenarios and reusable utilities.

A set of video tutorials is listed, covering topics such as obtaining HTTP request objects, sending requests, parsing responses, GET/POST practice, and handling headers and cookies.

The article introduces the FunRequest class, which combines a creator‑pattern single‑interface request framework with static methods copy and save for cloning request objects and persisting request/response data. It encapsulates request type, host, API name, URI, headers, GET arguments, POST parameters, JSON bodies, and response handling.

The full source code of the FunRequest class is provided, showing fields, fluent setters, header management, request building logic, response retrieval, cloning, and utility methods for initializing from an existing HttpRequestBase, copying, and saving.

package com.fun.frame.httpclient

import com.alibaba.fastjson.JSONObject
import com.fun.base.bean.RequestInfo
import com.fun.base.exception.RequestException
import com.fun.config.HttpClientConstant
import com.fun.config.RequestType
import com.fun.frame.Save
import com.fun.utils.Time
import org.apache.commons.lang3.StringUtils
import org.apache.http.Header
import org.apache.http.HttpEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.client.methods.RequestBuilder
import org.apache.http.util.EntityUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * 重写FanLibrary,使用面对对象思想
 */
class FunRequest extends FanLibrary implements Serializable, Cloneable {
    private static final long serialVersionUID = -4153600036943378727L;
    static Logger logger = LoggerFactory.getLogger(FunRequest.class)

    /** 请求类型,true为get,false为post */
    RequestType requestType

    /** 请求对象 */
    HttpRequestBase request

    /** host地址 */
    String host = EMPTY

    /** 接口地址 */
    String apiName = EMPTY

    /** 请求地址,如果为空则由host和apiname拼接 */
    String uri = EMPTY

    /** header集合 */
    List<Header> headers = new ArrayList<>()

    /** get参数 */
    JSONObject args = new JSONObject()

    /** post参数,表单 */
    JSONObject params = new JSONObject()

    /** json参数 */
    JSONObject json = new JSONObject()

    /** 响应,若没有这个参数,从将funrequest对象转换成json对象时会自动调用getresponse方法 */
    JSONObject response = new JSONObject()

    private FunRequest(RequestType requestType) {
        this.requestType = requestType
    }

    static FunRequest isGet() {
        new FunRequest(RequestType.GET)
    }

    static FunRequest isPost() {
        new FunRequest(RequestType.POST)
    }

    FunRequest setHost(String host) {
        this.host = host
        this
    }

    FunRequest setApiName(String apiName) {
        this.apiName = apiName
        this
    }

    FunRequest setUri(String uri) {
        this.uri = uri
        this
    }

    FunRequest addArgs(Object key, Object value) {
        args.put(key, value)
        this
    }

    FunRequest addParam(Object key, Object value) {
        params.put(key, value)
        this
    }

    FunRequest addJson(Object key, Object value) {
        json.put(key, value)
        this
    }

    FunRequest addHeader(Object key, Object value) {
        headers << getHeader(key.toString(), value.toString())
        this
    }

    public FunRequest addHeader(Header header) {
        headers.add(header)
        this
    }

    FunRequest addHeader(List<Header> header) {
        header.each { h -> headers << h }
        this
    }

    FunRequest addCookies(JSONObject cookies) {
        headers << getCookies(cookies)
        this
    }

    FunRequest setHeaders(List<Header> headers) {
        this.headers.addAll(headers)
        this
    }

    FunRequest setArgs(JSONObject args) {
        this.args.putAll(args)
        this
    }

    FunRequest setParams(JSONObject params) {
        this.params.putAll(params)
        this
    }

    FunRequest setJson(JSONObject json) {
        this.json.putAll(json)
        this
    }

    JSONObject getResponse() {
        response = response.isEmpty() ? getHttpResponse(request == null ? getRequest() : request) : response
        response
    }

    HttpRequestBase getRequest() {
        if (request != null) request;
        if (StringUtils.isEmpty(uri))
            uri = host + apiName
        switch (requestType) {
            case RequestType.GET:
                request = FanLibrary.getHttpGet(uri, args)
                break
            case RequestType.POST:
                request = !params.isEmpty() ? FanLibrary.getHttpPost(uri + changeJsonToArguments(args), params) : !json.isEmpty() ? getHttpPost(uri + changeJsonToArguments(args), json.toString()) : getHttpPost(uri + changeJsonToArguments(args))
                break
        }
        for (Header header in headers) {
            request.addHeader(header)
        }
        logger.debug("请求信息:{}", new RequestInfo(this.request).toString())
        request
    }

    @Override
    FunRequest clone() {
        initFromRequest(this.getRequest())
    }

    @Override
    public String toString() {
        return "{" +
                "requestType='" + requestType.getName() + '\'' +
                ", host='" + host + '\'' +
                ", apiName='" + apiName + '\'' +
                ", uri='" + uri + '\'' +
                ", headers=" + header2Json(headers).toString() +
                ", args=" + args.toString() +
                ", params=" + params.toString() +
                ", json=" + json.toString() +
                ", response=" + getResponse().toString() +
                "}"
    }

    static FunRequest initFromRequest(HttpRequestBase base) {
        FunRequest request = null;
        String method = base.getMethod();
        RequestType requestType = RequestType.getRequestType(method);
        String uri = base.getURI().toString();
        List<Header> headers = Arrays.asList(base.getAllHeaders());
        if (requestType == requestType.GET) {
            request = FunRequest.isGet().setUri(uri).setHeaders(headers);
        } else if (requestType == RequestType.POST || requestType == RequestType.FUN) {
            HttpPost post = (HttpPost) base;
            HttpEntity entity = post.getEntity();
            String value = entity.getContentType().getValue();
            String content = null;
            try {
                content = EntityUtils.toString(entity);
            } catch (IOException e) {
                logger.error("解析响应失败!", e)
                fail();
            }
            if (value.equalsIgnoreCase(HttpClientConstant.ContentType_TEXT.getValue()) || value.equalsIgnoreCase(HttpClientConstant.ContentType_JSON.getValue())) {
                request = FunRequest.isPost().setUri(uri).setHeaders(headers).setJson(JSONObject.parseObject(content));
            } else if (value.equalsIgnoreCase(HttpClientConstant.ContentType_FORM.getValue())) {
                request = FunRequest.isPost().setUri(uri).setHeaders(headers).setParams(getJson(content.split("&")));
            }
        } else {
            RequestException.fail("不支持的请求类型!");
        }
        return request;
    }

    static HttpRequestBase doCopy(HttpRequestBase base) {
        (HttpRequestBase) RequestBuilder.copy(base).build()
    }

    static HttpRequestBase cloneRequest(HttpRequestBase base) {
        initFromRequest(base).getRequest()
    }

    public static void save(HttpRequestBase base, JSONObject response) {
        FunRequest request = initFromRequest(base)
        request.setResponse(response);
        Save.info("/request/" + Time.getDate().substring(8) + SPACE_1 + request.getUri().replace(OR, CONNECTOR).replaceAll("https*:_+", EMPTY), request.toString());
    }
}

A disclaimer notes that the article originally appeared on the “FunTester” public account and should not be republished without permission.

Additional curated technical and non‑code articles are listed for further exploration.

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.

JavatestingHTTPAPIFramework
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.