7 Commits
Author SHA1 Message Date
Timi 1d09b8315b v0.2.0
CI/CD / build-deploy (pull_request) Successful in 12s
2026-10-01 21:28:03 +08:00
Timi 8287d6eedd RESTful design 2026-10-01 21:27:50 +08:00
Timi 113cdeb0d9 v0.1.0
CI/CD / build-deploy (pull_request) Successful in 11s
2026-10-01 18:46:29 +08:00
Timi 82d71057dd v0.0.14
CI/CD / build-deploy (pull_request) Successful in 13s
2026-08-07 15:45:17 +08:00
Timi 34e4a733f7 add response callback 2026-08-07 15:45:08 +08:00
Timi 2763e0d091 v0.0.13
CI/CD / build-deploy (pull_request) Successful in 42s
2026-07-23 15:10:44 +08:00
Timi 3cfffc3e8d fix nullable header/timeout/url arg 2026-07-23 15:10:36 +08:00
9 changed files with 356 additions and 76 deletions
+12 -1
View File
@@ -1,3 +1,14 @@
# timi-network # timi-network
Java 网络操作工具 Java 网络操作工具
静态工厂方法按 HTTP 方法命名,支持 `get`、`post`、`put`、`patch`、`delete`、`head` 和 `options`,分别用于读取、创建、替换、部分更新、删除资源、获取响应头和查询支持的请求方法
`CommonRequest`、`JacksonRequest`、`FileRequest` 和 `TimiRequest` 的工厂方法均返回对应类型,`ProgressiveRequest` 的工厂方法额外接收进度回调
```java
JacksonRequest.put("https://example.com/users/1").body(user).execute();
JacksonRequest.patch("https://example.com/users/1").body(changes).execute();
CommonRequest.delete("https://example.com/users/1").execute();
long length = FileRequest.head("https://example.com/files/1").length();
```
+2 -2
View File
@@ -6,7 +6,7 @@
<groupId>com.imyeyu.network</groupId> <groupId>com.imyeyu.network</groupId>
<artifactId>timi-network</artifactId> <artifactId>timi-network</artifactId>
<version>0.0.12</version> <version>0.2.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<properties> <properties>
@@ -106,7 +106,7 @@
<dependency> <dependency>
<groupId>com.imyeyu.io</groupId> <groupId>com.imyeyu.io</groupId>
<artifactId>timi-io</artifactId> <artifactId>timi-io</artifactId>
<version>0.0.5</version> <version>0.1.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents.client5</groupId> <groupId>org.apache.httpcomponents.client5</groupId>
+21 -22
View File
@@ -1,5 +1,6 @@
package com.imyeyu.network; package com.imyeyu.network;
import com.imyeyu.java.TimiJava;
import com.imyeyu.utils.Encoder; import com.imyeyu.utils.Encoder;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.fluent.Form; import org.apache.hc.client5.http.fluent.Form;
@@ -29,7 +30,7 @@ public class ArgMap<K, V> {
private final List<Map.Entry<K, V>> entries = new ArrayList<>(); private final List<Map.Entry<K, V>> entries = new ArrayList<>();
/** /**
* 追加一个参数。 * 追加一个参数
* *
* @param key 参数名 * @param key 参数名
* @param value 参数值 * @param value 参数值
@@ -41,7 +42,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 按插入顺序遍历全部参数。 * 按插入顺序遍历全部参数
* *
* @param consumer 处理逻辑 * @param consumer 处理逻辑
*/ */
@@ -50,29 +51,29 @@ public class ArgMap<K, V> {
} }
/** /**
* 按插入顺序遍历全部非空参数。 * 按插入顺序遍历全部非空参数
* *
* @param consumer 处理逻辑 * @param consumer 处理逻辑
*/ */
private void forEachNonNull(BiConsumer<? super K, ? super V> consumer) { private void forEachNonNull(BiConsumer<? super K, ? super V> consumer) {
entries.forEach(entry -> { entries.forEach(entry -> {
if (entry.getValue() != null) { if (TimiJava.isNotEmpty(entry.getValue())) {
consumer.accept(entry.getKey(), entry.getValue()); consumer.accept(entry.getKey(), entry.getValue());
} }
}); });
} }
/** /**
* 是否存在可输出的非空参数。 * 是否存在可输出的非空参数
* *
* @return 是否存在非空参数 * @return true 为存在非空参数
*/ */
private boolean hasNonNullValue() { private boolean hasNonNullValue() {
return entries.stream().anyMatch(entry -> entry.getValue() != null); return entries.stream().anyMatch(entry -> TimiJava.isNotEmpty(entry.getValue()));
} }
/** /**
* 返回参数数量。 * 参数数量
* *
* @return 参数数量 * @return 参数数量
*/ */
@@ -81,23 +82,21 @@ public class ArgMap<K, V> {
} }
/** /**
* 判断参数列表是否为空。 * 判断参数列表是否为空
* *
* @return 是否为空 * @return true 为空
*/ */
public boolean isEmpty() { public boolean isEmpty() {
return entries.isEmpty(); return entries.isEmpty();
} }
/** /** 清空全部参数 */
* 清空全部参数。
*/
public void clear() { public void clear() {
entries.clear(); entries.clear();
} }
/** /**
* 返回只读参数视图。 * 返回只读参数视图
* *
* @return 参数条目列表 * @return 参数条目列表
*/ */
@@ -106,7 +105,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 转换为 multipart 实体。 * 转换为 multipart 实体
* *
* @return multipart 请求体 * @return multipart 请求体
*/ */
@@ -125,7 +124,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 转换为表单参数列表。 * 转换为表单参数列表
* *
* @return 表单参数列表 * @return 表单参数列表
*/ */
@@ -136,9 +135,9 @@ public class ArgMap<K, V> {
} }
/** /**
* 转换为 query string。 * 转换为 URL 查询参数
* *
* @return query string * @return URL 查询参数
*/ */
public String toURL() { public String toURL() {
if (!hasNonNullValue()) { if (!hasNonNullValue()) {
@@ -151,7 +150,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 将参数拼接到指定 URL。 * 将参数拼接到指定 URL
* *
* @param url 原始 URL * @param url 原始 URL
* @return 拼接后的 URL * @return 拼接后的 URL
@@ -173,7 +172,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 使用一组参数创建对象。 * 使用一组参数创建对象
* *
* @param key 参数名 * @param key 参数名
* @param value 参数值 * @param value 参数值
@@ -186,7 +185,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 使用两组参数创建对象。 * 使用两组参数创建对象
* *
* @param key1 参数名 1 * @param key1 参数名 1
* @param value1 参数值 1 * @param value1 参数值 1
@@ -201,7 +200,7 @@ public class ArgMap<K, V> {
} }
/** /**
* 使用三组参数创建对象。 * 使用三组参数创建对象
* *
* @param key1 参数名 1 * @param key1 参数名 1
* @param value1 参数值 1 * @param value1 参数值 1
@@ -1,7 +1,12 @@
package com.imyeyu.network; 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.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpEntity; 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 org.apache.hc.core5.util.Timeout;
import java.io.IOException; import java.io.IOException;
@@ -15,6 +20,9 @@ public class CommonRequest {
protected final Request request; protected final Request request;
/// 响应回调
protected CallbackArg<HttpResponse> responseCallback;
protected CommonRequest(Request request) { protected CommonRequest(Request request) {
this.request = request; this.request = request;
} }
@@ -31,23 +39,74 @@ public class CommonRequest {
return new CommonRequest(Request.post(url)); return new CommonRequest(Request.post(url));
} }
/// 创建 PUT 请求,用于替换资源
///
/// @param url 请求地址
/// @return CommonRequest 请求
public static CommonRequest put(String url) {
return new CommonRequest(Request.put(url));
}
/// 创建 PATCH 请求,用于部分更新资源
///
/// @param url 请求地址
/// @return CommonRequest 请求
public static CommonRequest patch(String url) {
return new CommonRequest(Request.patch(url));
}
/// 创建 DELETE 请求,用于删除资源
///
/// @param url 请求地址
/// @return CommonRequest 请求
public static CommonRequest delete(String url) {
return new CommonRequest(Request.delete(url));
}
/// 创建 HEAD 请求,用于获取响应头
///
/// @param url 请求地址
/// @return CommonRequest 请求
public static CommonRequest head(String url) {
return new CommonRequest(Request.head(url));
}
/// 创建 OPTIONS 请求,用于查询支持的请求方法
///
/// @param url 请求地址
/// @return CommonRequest 请求
public static CommonRequest options(String url) {
return new CommonRequest(Request.options(url));
}
public CommonRequest timeout(long ms) { public CommonRequest timeout(long ms) {
request.connectTimeout(Timeout.ofMilliseconds(ms)).responseTimeout(Timeout.ofMilliseconds(ms)); if (0 < ms) {
request.connectTimeout(Timeout.ofMilliseconds(ms)).responseTimeout(Timeout.ofMilliseconds(ms));
}
return this; return this;
} }
public CommonRequest header(String key, String value) { public CommonRequest header(String key, String value) {
request.addHeader(key, value); if (TimiJava.isNotEmpty(value)) {
request.addHeader(key, value);
}
return this; return this;
} }
public CommonRequest token(String token) { public CommonRequest token(String token) {
request.addHeader("Token", token); return header("Token", token);
return this;
} }
public CommonRequest language(String langHeader) { public CommonRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader); return header("Accept-Language", langHeader);
}
/// 设置响应回调,回调在响应体读取前执行
///
/// @param callback 响应回调,传入 null 表示移除回调
/// @return 当前请求
public CommonRequest responseCallback(CallbackArg<HttpResponse> callback) {
this.responseCallback = callback;
return this; return this;
} }
@@ -57,7 +116,7 @@ public class CommonRequest {
} }
public String asString() throws IOException { public String asString() throws IOException {
return request.execute().returnContent().asString(); return handleResponse(response -> new ContentResponseHandler().handleResponse(response).asString());
} }
public Number asNumber() throws IOException { public Number asNumber() throws IOException {
@@ -65,14 +124,29 @@ public class CommonRequest {
} }
public byte[] asBytes() throws IOException { public byte[] asBytes() throws IOException {
return request.execute().returnContent().asBytes(); return handleResponse(response -> new ContentResponseHandler().handleResponse(response).asBytes());
} }
public InputStream asStream() throws IOException { public InputStream asStream() throws IOException {
return request.execute().returnContent().asStream(); return handleResponse(response -> new ContentResponseHandler().handleResponse(response).asStream());
} }
public void execute() throws IOException { 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);
});
} }
} }
@@ -1,6 +1,7 @@
package com.imyeyu.network; package com.imyeyu.network;
import com.imyeyu.io.IO; import com.imyeyu.io.IO;
import com.imyeyu.java.bean.CallbackArg;
import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpEntity;
@@ -35,6 +36,46 @@ public class FileRequest extends JacksonRequest {
return new FileRequest(Request.post(url)); return new FileRequest(Request.post(url));
} }
/// 创建 PUT 请求,用于替换资源
///
/// @param url 请求地址
/// @return FileRequest 请求
public static FileRequest put(String url) {
return new FileRequest(Request.put(url));
}
/// 创建 PATCH 请求,用于部分更新资源
///
/// @param url 请求地址
/// @return FileRequest 请求
public static FileRequest patch(String url) {
return new FileRequest(Request.patch(url));
}
/// 创建 DELETE 请求,用于删除资源
///
/// @param url 请求地址
/// @return FileRequest 请求
public static FileRequest delete(String url) {
return new FileRequest(Request.delete(url));
}
/// 创建 HEAD 请求,用于获取响应头
///
/// @param url 请求地址
/// @return FileRequest 请求
public static FileRequest head(String url) {
return new FileRequest(Request.head(url));
}
/// 创建 OPTIONS 请求,用于查询支持的请求方法
///
/// @param url 请求地址
/// @return FileRequest 请求
public static FileRequest options(String url) {
return new FileRequest(Request.options(url));
}
@Override @Override
public FileRequest timeout(long ms) { public FileRequest timeout(long ms) {
super.timeout(ms); super.timeout(ms);
@@ -43,19 +84,25 @@ public class FileRequest extends JacksonRequest {
@Override @Override
public FileRequest header(String key, String value) { public FileRequest header(String key, String value) {
request.addHeader(key, value); super.header(key, value);
return this; return this;
} }
@Override @Override
public FileRequest token(String token) { public FileRequest token(String token) {
request.addHeader("Token", token); super.token(token);
return this; return this;
} }
@Override @Override
public FileRequest language(String langHeader) { public FileRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader); super.language(langHeader);
return this;
}
@Override
public FileRequest responseCallback(CallbackArg<HttpResponse> callback) {
super.responseCallback(callback);
return this; return this;
} }
@@ -84,15 +131,16 @@ public class FileRequest extends JacksonRequest {
} }
public long length() throws IOException, ProtocolException { public long length() throws IOException, ProtocolException {
HttpResponse response = request.execute().returnResponse(); return handleResponse(response -> {
final int status = response.getCode(); final int status = response.getCode();
if (status < 200 || 300 <= status) { if (status < 200 || 300 <= status) {
throw new IOException("HTTP error status: " + status); throw new IOException("HTTP error status: " + status);
} }
final Header contentLengthHeader = response.getHeader("Content-Length"); final Header contentLengthHeader = response.getHeader("Content-Length");
if (contentLengthHeader == null) { if (contentLengthHeader == null) {
throw new IOException("Content-Length header missing"); throw new IOException("Content-Length header missing");
} }
return Long.parseLong(contentLengthHeader.getValue()); return Long.parseLong(contentLengthHeader.getValue());
});
} }
} }
@@ -8,9 +8,11 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.java.bean.CallbackArg;
import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@@ -29,7 +31,7 @@ public class JacksonRequest extends CommonRequest {
static { static {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); OBJECT_MAPPER.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
} }
private ObjectMapper objectMapper = null; private ObjectMapper objectMapper = null;
@@ -80,6 +82,46 @@ public class JacksonRequest extends CommonRequest {
return new JacksonRequest(Request.post(url)); return new JacksonRequest(Request.post(url));
} }
/// 创建 PUT 请求,用于替换资源
///
/// @param url 请求地址
/// @return JacksonRequest 请求
public static JacksonRequest put(String url) {
return new JacksonRequest(Request.put(url));
}
/// 创建 PATCH 请求,用于部分更新资源
///
/// @param url 请求地址
/// @return JacksonRequest 请求
public static JacksonRequest patch(String url) {
return new JacksonRequest(Request.patch(url));
}
/// 创建 DELETE 请求,用于删除资源
///
/// @param url 请求地址
/// @return JacksonRequest 请求
public static JacksonRequest delete(String url) {
return new JacksonRequest(Request.delete(url));
}
/// 创建 HEAD 请求,用于获取响应头
///
/// @param url 请求地址
/// @return JacksonRequest 请求
public static JacksonRequest head(String url) {
return new JacksonRequest(Request.head(url));
}
/// 创建 OPTIONS 请求,用于查询支持的请求方法
///
/// @param url 请求地址
/// @return JacksonRequest 请求
public static JacksonRequest options(String url) {
return new JacksonRequest(Request.options(url));
}
/** /**
* 指定对象映射器。 * 指定对象映射器。
* *
@@ -99,24 +141,30 @@ public class JacksonRequest extends CommonRequest {
@Override @Override
public JacksonRequest header(String key, String value) { public JacksonRequest header(String key, String value) {
request.addHeader(key, value); super.header(key, value);
return this; return this;
} }
@Override @Override
public JacksonRequest token(String token) { public JacksonRequest token(String token) {
request.addHeader("Token", token); super.token(token);
return this; return this;
} }
@Override @Override
public JacksonRequest language(String langHeader) { public JacksonRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader); super.language(langHeader);
return this;
}
@Override
public JacksonRequest responseCallback(CallbackArg<HttpResponse> callback) {
super.responseCallback(callback);
return this; return this;
} }
/** /**
* 设置 JSON 请求体。 * 设置 JSON 请求体
* *
* @param object 要序列化的对象 * @param object 要序列化的对象
* @return 当前请求 * @return 当前请求
@@ -2,9 +2,10 @@ package com.imyeyu.network;
import com.imyeyu.io.IO; import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArg;
import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.client5.http.fluent.Response;
import org.apache.hc.core5.http.HttpEntity; 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.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.EntityUtils;
@@ -42,6 +43,51 @@ public class ProgressiveRequest extends FileRequest {
return new ProgressiveRequest(Request.post(url), callback); return new ProgressiveRequest(Request.post(url), callback);
} }
/// 创建 PUT 请求,用于替换资源
///
/// @param url 请求地址
/// @param callback 进度回调
/// @return ProgressiveRequest 请求
public static ProgressiveRequest put(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.put(url), callback);
}
/// 创建 PATCH 请求,用于部分更新资源
///
/// @param url 请求地址
/// @param callback 进度回调
/// @return ProgressiveRequest 请求
public static ProgressiveRequest patch(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.patch(url), callback);
}
/// 创建 DELETE 请求,用于删除资源
///
/// @param url 请求地址
/// @param callback 进度回调
/// @return ProgressiveRequest 请求
public static ProgressiveRequest delete(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.delete(url), callback);
}
/// 创建 HEAD 请求,用于获取响应头
///
/// @param url 请求地址
/// @param callback 进度回调
/// @return ProgressiveRequest 请求
public static ProgressiveRequest head(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.head(url), callback);
}
/// 创建 OPTIONS 请求,用于查询支持的请求方法
///
/// @param url 请求地址
/// @param callback 进度回调
/// @return ProgressiveRequest 请求
public static ProgressiveRequest options(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.options(url), callback);
}
@Override @Override
public ProgressiveRequest timeout(long ms) { public ProgressiveRequest timeout(long ms) {
super.timeout(ms); super.timeout(ms);
@@ -50,19 +96,25 @@ public class ProgressiveRequest extends FileRequest {
@Override @Override
public ProgressiveRequest header(String key, String value) { public ProgressiveRequest header(String key, String value) {
request.addHeader(key, value); super.header(key, value);
return this; return this;
} }
@Override @Override
public ProgressiveRequest token(String token) { public ProgressiveRequest token(String token) {
request.addHeader("Token", token); super.token(token);
return this; return this;
} }
@Override @Override
public ProgressiveRequest language(String langHeader) { public ProgressiveRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader); super.language(langHeader);
return this;
}
@Override
public ProgressiveRequest responseCallback(CallbackArg<HttpResponse> callback) {
super.responseCallback(callback);
return this; return this;
} }
@@ -80,12 +132,12 @@ public class ProgressiveRequest extends FileRequest {
@Override @Override
public void toFile(Path outputPath) throws IOException, NoPermissionException { public void toFile(Path outputPath) throws IOException, NoPermissionException {
processResponse(request.execute(), IO.getOutputStream(outputPath.toFile())); processResponse(IO.getOutputStream(outputPath.toFile()));
} }
@Override @Override
public void toFile(File file) throws IOException, NoPermissionException { public void toFile(File file) throws IOException, NoPermissionException {
processResponse(request.execute(), IO.getOutputStream(file)); processResponse(IO.getOutputStream(file));
} }
@Override @Override
@@ -96,17 +148,17 @@ public class ProgressiveRequest extends FileRequest {
@Override @Override
public byte[] asBytes() throws IOException { public byte[] asBytes() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream();
processResponse(request.execute(), os); processResponse(os);
return os.toByteArray(); return os.toByteArray();
} }
private void processResponse(Response response, OutputStream os) throws IOException { private void processResponse(OutputStream os) throws IOException {
response.handleResponse((HttpClientResponseHandler<Void>) resp -> { handleResponse((HttpClientResponseHandler<Void>) response -> {
HttpEntity entity = resp.getEntity(); HttpEntity entity = response.getEntity();
if (entity == null) { if (entity == null) {
throw new IOException("not found response entity"); throw new IOException("not found response entity");
} }
int code = resp.getCode(); int code = response.getCode();
if (400 <= code) { if (400 <= code) {
throw new IOException("response error: %s".formatted(code)); throw new IOException("response error: %s".formatted(code));
} }
@@ -2,9 +2,11 @@ package com.imyeyu.network;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JavaType;
import com.imyeyu.java.bean.timi.TimiResponse; import com.imyeyu.java.bean.CallbackArg;
import com.imyeyu.java.bean.Response;
import org.apache.hc.client5.http.fluent.Request; import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@@ -31,6 +33,46 @@ public class TimiRequest extends JacksonRequest {
return new TimiRequest(Request.post(url)); return new TimiRequest(Request.post(url));
} }
/// 创建 PUT 请求,用于替换资源
///
/// @param url 请求地址
/// @return TimiRequest 请求
public static TimiRequest put(String url) {
return new TimiRequest(Request.put(url));
}
/// 创建 PATCH 请求,用于部分更新资源
///
/// @param url 请求地址
/// @return TimiRequest 请求
public static TimiRequest patch(String url) {
return new TimiRequest(Request.patch(url));
}
/// 创建 DELETE 请求,用于删除资源
///
/// @param url 请求地址
/// @return TimiRequest 请求
public static TimiRequest delete(String url) {
return new TimiRequest(Request.delete(url));
}
/// 创建 HEAD 请求,用于获取响应头
///
/// @param url 请求地址
/// @return TimiRequest 请求
public static TimiRequest head(String url) {
return new TimiRequest(Request.head(url));
}
/// 创建 OPTIONS 请求,用于查询支持的请求方法
///
/// @param url 请求地址
/// @return TimiRequest 请求
public static TimiRequest options(String url) {
return new TimiRequest(Request.options(url));
}
@Override @Override
public TimiRequest timeout(long ms) { public TimiRequest timeout(long ms) {
super.timeout(ms); super.timeout(ms);
@@ -39,19 +81,25 @@ public class TimiRequest extends JacksonRequest {
@Override @Override
public TimiRequest header(String key, String value) { public TimiRequest header(String key, String value) {
request.addHeader(key, value); super.header(key, value);
return this; return this;
} }
@Override @Override
public TimiRequest token(String token) { public TimiRequest token(String token) {
request.addHeader("Token", token); super.token(token);
return this; return this;
} }
@Override @Override
public TimiRequest language(String langHeader) { public TimiRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader); super.language(langHeader);
return this;
}
@Override
public TimiRequest responseCallback(CallbackArg<HttpResponse> callback) {
super.responseCallback(callback);
return this; return this;
} }
@@ -86,7 +134,7 @@ public class TimiRequest extends JacksonRequest {
* @throws IOException 读取或解析失败 * @throws IOException 读取或解析失败
*/ */
public <T> T resultAs(Class<T> clazz) throws IOException { public <T> T resultAs(Class<T> clazz) throws IOException {
TimiResponse<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(clazz)); Response<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(clazz));
if (resp.isFail()) { if (resp.isFail()) {
throw resp.toException(); throw resp.toException();
} }
@@ -102,7 +150,7 @@ public class TimiRequest extends JacksonRequest {
* @throws IOException 读取或解析失败 * @throws IOException 读取或解析失败
*/ */
public <T> T resultAs(TypeReference<T> typeReference) throws IOException { public <T> T resultAs(TypeReference<T> typeReference) throws IOException {
TimiResponse<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(typeReference)); Response<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(typeReference));
if (resp.isFail()) { if (resp.isFail()) {
throw resp.toException(); throw resp.toException();
} }
@@ -118,7 +166,7 @@ public class TimiRequest extends JacksonRequest {
* @throws IOException 读取或解析失败 * @throws IOException 读取或解析失败
*/ */
public <T> T resultAs(Type type) throws IOException { public <T> T resultAs(Type type) throws IOException {
TimiResponse<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(type)); Response<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(type));
if (resp.isFail()) { if (resp.isFail()) {
throw resp.toException(); throw resp.toException();
} }
@@ -127,7 +175,7 @@ public class TimiRequest extends JacksonRequest {
@Override @Override
public void execute() throws IOException { public void execute() throws IOException {
TimiResponse<?> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(Object.class)); Response<?> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(Object.class));
if (resp.isFail()) { if (resp.isFail()) {
throw resp.toException(); throw resp.toException();
} }
@@ -140,7 +188,7 @@ public class TimiRequest extends JacksonRequest {
* @return Jackson 类型 * @return Jackson 类型
*/ */
protected JavaType timiResponseType(Class<?> clazz) { protected JavaType timiResponseType(Class<?> clazz) {
return getObjectMapper().getTypeFactory().constructParametricType(TimiResponse.class, clazz); return getObjectMapper().getTypeFactory().constructParametricType(Response.class, clazz);
} }
/** /**
@@ -150,7 +198,7 @@ public class TimiRequest extends JacksonRequest {
* @return Jackson 类型 * @return Jackson 类型
*/ */
protected JavaType timiResponseType(TypeReference<?> typeReference) { protected JavaType timiResponseType(TypeReference<?> typeReference) {
return getObjectMapper().getTypeFactory().constructParametricType(TimiResponse.class, getObjectMapper().constructType(typeReference)); return getObjectMapper().getTypeFactory().constructParametricType(Response.class, getObjectMapper().constructType(typeReference));
} }
/** /**
@@ -160,6 +208,6 @@ public class TimiRequest extends JacksonRequest {
* @return Jackson 类型 * @return Jackson 类型
*/ */
protected JavaType timiResponseType(Type type) { protected JavaType timiResponseType(Type type) {
return getObjectMapper().getTypeFactory().constructParametricType(TimiResponse.class, getObjectMapper().constructType(type)); return getObjectMapper().getTypeFactory().constructParametricType(Response.class, getObjectMapper().constructType(type));
} }
} }
@@ -28,7 +28,7 @@ public class ProgressRequestTest {
@Test @Test
public void testLength() throws Exception { public void testLength() throws Exception {
long length = FileRequest.wrap(Request.head(URL2)).length(); long length = FileRequest.head(URL2).length();
System.out.println(IOSize.format(length)); System.out.println(IOSize.format(length));
} }
@@ -38,4 +38,4 @@ public class ProgressRequestTest {
final Header contentLengthHeader = response.getHeader("Content-Length"); final Header contentLengthHeader = response.getHeader("Content-Length");
System.out.println(contentLengthHeader.getValue()); System.out.println(contentLengthHeader.getValue());
} }
} }