add response callback

This commit is contained in:
Timi
2026-08-07 15:45:08 +08:00
parent 2763e0d091
commit 34e4a733f7
5 changed files with 84 additions and 22 deletions
@@ -1,8 +1,12 @@
package com.imyeyu.network;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArg;
import org.apache.hc.client5.http.fluent.ContentResponseHandler;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.util.Timeout;
import java.io.IOException;
@@ -16,6 +20,9 @@ public class CommonRequest {
protected final Request request;
/// 响应回调
protected CallbackArg<HttpResponse> responseCallback;
protected CommonRequest(Request request) {
this.request = request;
}
@@ -54,13 +61,22 @@ public class CommonRequest {
return header("Accept-Language", langHeader);
}
/// 设置响应回调,回调在响应体读取前执行
///
/// @param callback 响应回调,传入 null 表示移除回调
/// @return 当前请求
public CommonRequest responseCallback(CallbackArg<HttpResponse> callback) {
this.responseCallback = callback;
return this;
}
public CommonRequest bodyEntity(HttpEntity entity) {
request.body(entity);
return this;
}
public String asString() throws IOException {
return request.execute().returnContent().asString();
return handleResponse(response -> new ContentResponseHandler().handleResponse(response).asString());
}
public Number asNumber() throws IOException {
@@ -68,14 +84,29 @@ public class CommonRequest {
}
public byte[] asBytes() throws IOException {
return request.execute().returnContent().asBytes();
return handleResponse(response -> new ContentResponseHandler().handleResponse(response).asBytes());
}
public InputStream asStream() throws IOException {
return request.execute().returnContent().asStream();
return handleResponse(response -> new ContentResponseHandler().handleResponse(response).asStream());
}
public void execute() throws IOException {
request.execute();
handleResponse(response -> null);
}
/// 使用统一入口处理响应,子类的自定义响应处理必须调用此方法
///
/// @param handler 响应处理器
/// @param <T> 返回值类型
/// @return 响应处理结果
/// @throws IOException 请求或响应处理失败
protected <T> T handleResponse(HttpClientResponseHandler<T> handler) throws IOException {
return request.execute().handleResponse(response -> {
if (responseCallback != null) {
responseCallback.handler(response);
}
return handler.handleResponse(response);
});
}
}