A Linear‑Style Java API Request Framework Using HttpClient
The article introduces a straight‑line (linear) code‑style Java framework for building and executing HTTP API requests, explains its design, provides the full source code, and demonstrates usage with a concise example illustrating GET/POST handling, headers, cookies, and response parsing.
During Java‑based API testing the author noticed Java’s verbosity compared to scripting languages like Python and explored a "straight‑line" coding style, then implemented a linear‑style request framework to simplify HTTP calls.
The framework, named FunRequest, extends a base FanLibrary and encapsulates request type, host, API name, URI, headers, GET/POST parameters, JSON bodies, and cookies. It provides static factory methods isGet() and isPost() to create request instances, fluent setters for configuration, and methods to add arguments, parameters, JSON data, headers, and cookies. The getResponse() method builds the final URI, selects the appropriate HttpClient request (GET or POST), attaches headers, and returns the JSON response.
The complete source code is:
package com.fun.frame.httpclient
import com.fun.base.bean.RequestInfo
import com.fun.config.RequestType
import net.sf.json.JSONObject
import org.apache.commons.lang3.StringUtils
import org.apache.http.Header
import org.apache.http.client.methods.HttpRequestBase
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* 重写FanLibrary,使用面对对象思想
*/
public class FunRequest extends FanLibrary {
static Logger logger = LoggerFactory.getLogger(FunRequest.class)
/** 请求类型,true为get,false为post */
RequestType requestType
/** 请求对象 */
HttpRequestBase request
/** host地址 */
String host
/** 接口地址 */
String apiName
/** 请求地址,如果为空则由host和apiname拼接 */
String uri
/** header集合 */
List<Header> headers = new ArrayList<>()
/** get参数 */
JSONObject args = new JSONObject()
/** post参数 */
JSONObject params = new JSONObject()
/** json参数 */
JSONObject json = new JSONObject()
/** 构造方法 */
private FunRequest(RequestType requestType) {
this.requestType = requestType
}
/** 获取get对象 */
public static FunRequest isGet() {
new FunRequest(RequestType.GET)
}
/** 获取post对象 */
public static FunRequest isPost() {
new FunRequest(RequestType.POST)
}
/** 设置host */
public FunRequest setHost(String host) {
this.host = host
this
}
/** 设置接口地址 */
public FunRequest setApiName(String apiName) {
this.apiName = apiName
this
}
/** 设置uri */
public FunRequest setUri(String uri) {
this.uri = uri
this
}
/** 添加get参数 */
public FunRequest addArgs(Object key, Object value) {
args.put(key, value)
this
}
/** 添加post参数 */
public FunRequest addParam(Object key, Object value) {
params.put(key, value)
this
}
/** 添加json参数 */
public FunRequest addJson(Object key, Object value) {
json.put(key, value)
this
}
/** 添加header */
public FunRequest addHeader(Object key, Object value) {
headers << getHeader(key.toString(), value.toString())
this
}
/** 添加header */
public FunRequest addHeader(Header header) {
headers.add(header)
this
}
/** 批量添加header */
public FunRequest addHeader(List<Header> header) {
header.each { h -> headers << h }
this
}
/** 增加header中cookies */
public FunRequest addCookies(JSONObject cookies) {
headers << getCookies(cookies)
this
}
/** 获取请求响应,兼容相关参数方法,不包括file */
public JSONObject getResponse() {
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
}
headers.each { x -> request.addHeader(x) }
return getHttpResponse(request)
}
/** 获取请求对象 */
public HttpRequestBase getRequest() {
logger.debug("请求信息:{}", new RequestInfo(this.request).toString())
this.request
}
@Override
public String toString() {
JSONObject.fromObject(this).toString()
}
}Usage of the framework is demonstrated with a simple main method that builds a GET request, sets host, API path, query arguments, a header, cookies, and then obtains and outputs the JSON response.
public static void main(String[] args) {
JSONObject response = FunRequest.isGet()
.setHost("www.funtester.cn")
.setApiName("/test")
.addArgs("uname", "FunTester")
.addArgs("passoword", "FunTester")
.addArgs("type", "FunTester")
.addHeader("token", "FunTester")
.addCookies(getJson("login=false"))
.getResponse();
output(response);
FanLibrary.testOver();
}The article concludes with a curated list of technical and non‑technical articles for further reading.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
