24 Commits

Author SHA1 Message Date
01074e1ac2 Merge pull request 'v0.0.5' (#5) from dev into master
Reviewed-on: #5
2026-03-16 09:13:40 +00:00
Timi
ada0f96e57 v0.0.5
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 3m4s
2026-03-16 17:13:10 +08:00
Timi
ef7b9af9b7 add bodyEntity 2026-03-16 16:34:46 +08:00
1b60210c06 Merge pull request 'v0.0.4' (#4) from dev into master
Reviewed-on: #4
2026-03-09 03:14:26 +00:00
Timi
436ac6f205 v0.0.4
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 21s
2026-03-09 11:14:12 +08:00
2290ac5ecf Merge pull request 'v0.0.3' (#3) from dev into master
Reviewed-on: #3
2026-02-10 07:31:09 +00:00
Timi
45294b6299 v0.0.3
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 8s
2026-02-10 15:30:48 +08:00
6101e8d462 Merge pull request 'v0.0.3' (#2) from dev into master
Reviewed-on: #2
2026-02-10 07:22:43 +00:00
Timi
6ddd9928fc v0.0.3
Some checks failed
CI/CD / build-deploy (pull_request) Failing after 11s
2026-02-10 15:22:04 +08:00
aaea3a218b Merge pull request 'v0.0.2' (#1) from dev into master
Reviewed-on: #1
2026-01-19 10:00:36 +00:00
Timi
7b46d2c0c4 add CI workflow
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 1m16s
2026-01-19 17:58:03 +08:00
Timi
acb1304650 add CommonRequest.header 2025-11-07 23:38:25 +08:00
Timi
56afd301fb add CommonRequest.timeout 2025-11-07 22:50:44 +08:00
Timi
a240c00996 add CommonRequest.execute 2025-11-07 00:16:44 +08:00
Timi
fbcf21e990 add GsonRequest.body 2025-11-07 00:15:06 +08:00
Timi
f3623d03a2 support deploy nexus 2025-10-13 10:53:17 +08:00
Timi
e63d1103d8 add ProgressRequestTest 2025-10-13 10:53:00 +08:00
Timi
016c0b7e2f rename FormMap to ArgMap then support url arg 2025-10-13 10:52:48 +08:00
Timi
016e0b0962 extend CommonRequest for GsonRequest 2025-07-24 18:46:35 +08:00
Timi
91ef5e3bc3 fix GsonRequest serialize fail 2025-07-19 17:27:29 +08:00
Timi
12bb7603a1 add static get,post for ProgressiveRequest 2025-07-15 16:23:52 +08:00
Timi
77c32fb52f add CommonRequest, FileRequest, GsonRequest, TimiRequest 2025-07-15 16:23:34 +08:00
Timi
43919851ed add toFile(File) for ProgressiveRequest 2025-07-15 12:01:55 +08:00
Timi
9330c75bbc add length() for ProgressiveRequest 2025-07-15 11:57:58 +08:00
13 changed files with 1147 additions and 40 deletions

162
.gitea/workflows/ci.yml Normal file
View File

@@ -0,0 +1,162 @@
name: CI/CD
on:
pull_request:
branches:
- master
types:
- closed
jobs:
build-deploy:
runs-on: act_runner_java
if: ${{ github.event.pull_request.merged == true }}
env:
JAVA_HOME: /usr/lib/jvm/java-21-openjdk
steps:
- name: Checkout code
run: |
git clone ${{ github.server_url }}/${{ github.repository }}.git .
git checkout ${{ github.sha }}
- name: Set up environment
run: |
echo "PR #${{ github.event.number }} merged into master"
echo "Source branch: ${{ github.event.pull_request.head.ref }}"
echo "Target branch: ${{ github.event.pull_request.base.ref }}"
- name: Run tests
run: |
echo "Running test suite..."
- name: Build project
run: |
mvn -B -DskipTests clean package source:jar javadoc:jar
- name: Deploy to Nexus
if: success()
run: |
if [ -z "${{ secrets.NEXUS_USERNAME }}" ] || [ -z "${{ secrets.NEXUS_PASSWORD }}" ]; then
echo "Missing secrets.NEXUS_USERNAME or secrets.NEXUS_PASSWORD"
exit 1
fi
mkdir -p ~/.m2
cat > ~/.m2/settings.xml <<EOF
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<servers>
<server>
<id>timi-nexus</id>
<username>${{ secrets.NEXUS_USERNAME }}</username>
<password>${{ secrets.NEXUS_PASSWORD }}</password>
</server>
</servers>
</settings>
EOF
version=$(mvn -q -DforceStdout help:evaluate -Dexpression=project.version)
artifact_id=$(mvn -q -DforceStdout help:evaluate -Dexpression=project.artifactId)
main_jar="target/${artifact_id}-${version}.jar"
sources_jar="target/${artifact_id}-${version}-sources.jar"
javadoc_jar="target/${artifact_id}-${version}-javadoc.jar"
if [ ! -f "$main_jar" ] || [ ! -f "$sources_jar" ] || [ ! -f "$javadoc_jar" ]; then
echo "Missing build artifacts in target"
exit 1
fi
mvn -B deploy:deploy-file \
-Dfile="$main_jar" \
-Dsources="$sources_jar" \
-Djavadoc="$javadoc_jar" \
-DpomFile="./pom.xml" \
-Durl="https://nexus.imyeyu.com/repository/maven-releases/" \
-DrepositoryId="timi-nexus" \
-Dhttps.protocols=TLSv1.2 \
-Djdk.tls.client.protocols=TLSv1.2
- name: Create release
if: ${{ success() && startsWith(github.event.pull_request.title, 'v') }}
env:
GITEA_TOKEN: ${{ secrets.RUNNER_TOKEN }}
GITEA_SERVER_URL: ${{ github.server_url }}
GITEA_REPOSITORY: ${{ github.repository }}
RELEASE_TAG: ${{ github.event.pull_request.title }}
RELEASE_TARGET: ${{ github.sha }}
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "Missing secrets.RUNNER_TOKEN"
exit 1
fi
api_url="$GITEA_SERVER_URL/api/v1/repos/$GITEA_REPOSITORY/releases"
payload=$(cat <<EOF
{
"tag_name": "$RELEASE_TAG",
"name": "$RELEASE_TAG",
"target_commitish": "$RELEASE_TARGET",
"draft": false,
"prerelease": false
}
EOF
)
echo "Creating release with tag: $RELEASE_TAG"
echo "API URL: $api_url"
echo "Target commit: $RELEASE_TARGET"
http_code=$(curl -sS -w "%{http_code}" -o /tmp/release_response.json -X POST "$api_url" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/json" \
-d "$payload")
response=$(cat /tmp/release_response.json)
echo "HTTP Status: $http_code"
echo "Response: $response"
if [ "$http_code" -ne 201 ]; then
echo "Failed to create release (HTTP $http_code)"
if echo "$response" | grep -q "already exists"; then
echo "Release with tag $RELEASE_TAG already exists"
fi
exit 1
fi
release_id=$(echo "$response" | grep -oP '"id":\K[0-9]+' | head -n 1 || true)
if [ -z "$release_id" ]; then
echo "Failed to extract release ID from response"
exit 1
fi
echo "Release created: id=$release_id"
echo "Listing jar files in target directory:"
ls -lh target/*.jar || echo "No jar files found"
upload_count=0
for asset_path in target/*.jar; do
if [ ! -f "$asset_path" ]; then
echo "Skipping non-existent file: $asset_path"
continue
fi
asset_name=$(basename "$asset_path")
file_size=$(stat -c%s "$asset_path" 2>/dev/null || echo "unknown")
echo "Uploading asset: $asset_name (size: $file_size bytes)"
upload_url="$api_url/$release_id/assets?name=$asset_name"
echo "Upload URL: $upload_url"
set +e
http_code=$(curl -sS -w "%{http_code}" -o /tmp/asset_response.json -X POST "$upload_url" \
-H "Authorization: token $GITEA_TOKEN" \
-H "Content-Type: application/octet-stream" \
--data-binary @"$asset_path" 2>/dev/null)
curl_exit=$?
set -e
if [ $curl_exit -ne 0 ]; then
echo "✗ Curl failed with exit code $curl_exit for $asset_name"
cat /tmp/asset_response.json 2>/dev/null || echo "No response file"
continue
fi
if [ "$http_code" = "201" ]; then
echo "✓ Successfully uploaded: $asset_name"
upload_count=$((upload_count + 1))
else
echo "✗ Failed to upload $asset_name (HTTP $http_code)"
cat /tmp/asset_response.json 2>/dev/null || echo "No response body"
fi
done
echo "Upload complete: $upload_count file(s) uploaded"

4
.gitignore vendored
View File

@@ -1,3 +1,7 @@
AGENTS.md
CLAUDE.md
.claude
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/

94
pom.xml
View File

@@ -6,7 +6,7 @@
<groupId>com.imyeyu.network</groupId>
<artifactId>timi-network</artifactId>
<version>0.0.1</version>
<version>0.0.5</version>
<packaging>jar</packaging>
<properties>
@@ -16,16 +16,104 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.3</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.3.1</version>
</plugin>
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.18.20.0</version>
<configuration>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<outputDirectory>${project.build.directory}/delombok</outputDirectory>
<addOutputDirectory>false</addOutputDirectory>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>delombok</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.11.2</version>
<configuration>
<sourcepath>${project.build.directory}/delombok</sourcepath>
<encoding>UTF-8</encoding>
<charset>UTF-8</charset>
<docencoding>UTF-8</docencoding>
</configuration>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>timi_nexus</id>
<url>https://nexus.imyeyu.com/repository/maven-releases/</url>
</repository>
</distributionManagement>
<repositories>
<repository>
<id>timi_nexus</id>
<url>https://nexus.imyeyu.com/repository/maven-public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.imyeyu.io</groupId>
<artifactId>timi-io</artifactId>
<version>0.0.1</version>
<version>0.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5-fluent</artifactId>
<version>5.2.1</version>
<version>5.6</version>
</dependency>
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.40</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,196 @@
package com.imyeyu.network;
import com.imyeyu.utils.Encoder;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.fluent.Form;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import java.io.File;
import java.io.InputStream;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
/**
* 请求参数列表。
* <p>
* 该实现允许同名 key 重复出现,适用于 query 参数和表单参数场景。
*
* @author 夜雨
* @since 2025-06-26 15:41
*/
public class ArgMap<K, V> {
private final List<Map.Entry<K, V>> entries = new ArrayList<>();
/**
* 追加一个参数。
*
* @param key 参数名
* @param value 参数值
* @return 当前对象
*/
public ArgMap<K, V> put(K key, V value) {
entries.add(new AbstractMap.SimpleImmutableEntry<>(key, value));
return this;
}
/**
* 按插入顺序遍历全部参数。
*
* @param consumer 处理逻辑
*/
public void forEach(BiConsumer<? super K, ? super V> consumer) {
entries.forEach(entry -> consumer.accept(entry.getKey(), entry.getValue()));
}
/**
* 返回参数数量。
*
* @return 参数数量
*/
public int size() {
return entries.size();
}
/**
* 判断参数列表是否为空。
*
* @return 是否为空
*/
public boolean isEmpty() {
return entries.isEmpty();
}
/**
* 清空全部参数。
*/
public void clear() {
entries.clear();
}
/**
* 返回只读参数视图。
*
* @return 参数条目列表
*/
public List<Map.Entry<K, V>> entries() {
return Collections.unmodifiableList(entries);
}
/**
* 转换为 multipart 实体。
*
* @return multipart 请求体
*/
public HttpEntity toEntity() {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
forEach((k, v) -> {
String key = k.toString();
switch (v) {
case File file -> builder.addBinaryBody(key, file);
case byte[] bytes -> builder.addBinaryBody(key, bytes);
case InputStream stream -> builder.addBinaryBody(key, stream, ContentType.APPLICATION_OCTET_STREAM, key);
default -> builder.addTextBody(key, v.toString());
}
});
return builder.build();
}
/**
* 转换为表单参数列表。
*
* @return 表单参数列表
*/
public List<NameValuePair> toNameValuePair() {
Form form = Form.form();
forEach((k, v) -> form.add(k.toString(), v.toString()));
return form.build();
}
/**
* 转换为 query string。
*
* @return query string
*/
public String toURL() {
if (isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
forEach((k, v) -> sb.append(k.toString()).append('=').append(Encoder.urlArg(v.toString())).append('&'));
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* 将参数拼接到指定 URL。
*
* @param url 原始 URL
* @return 拼接后的 URL
*/
public String toURL(String url) {
if (isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.contains("?")) {
if (!url.endsWith("?") && !url.endsWith("&")) {
sb.append('&');
}
sb.append(toURL());
return sb.toString();
}
return url + "?" + toURL();
}
/**
* 使用一组参数创建对象。
*
* @param key 参数名
* @param value 参数值
* @param <K> key 类型
* @param <V> value 类型
* @return 参数对象
*/
public static <K, V> ArgMap<K, V> of(K key, V value) {
return new ArgMap<K, V>().put(key, value);
}
/**
* 使用两组参数创建对象。
*
* @param key1 参数名 1
* @param value1 参数值 1
* @param key2 参数名 2
* @param value2 参数值 2
* @param <K> key 类型
* @param <V> value 类型
* @return 参数对象
*/
public static <K, V> ArgMap<K, V> of(K key1, V value1, K key2, V value2) {
return new ArgMap<K, V>().put(key1, value1).put(key2, value2);
}
/**
* 使用三组参数创建对象。
*
* @param key1 参数名 1
* @param value1 参数值 1
* @param key2 参数名 2
* @param value2 参数值 2
* @param key3 参数名 3
* @param value3 参数值 3
* @param <K> key 类型
* @param <V> value 类型
* @return 参数对象
*/
public static <K, V> ArgMap<K, V> of(K key1, V value1, K key2, V value2, K key3, V value3) {
return new ArgMap<K, V>().put(key1, value1).put(key2, value2).put(key3, value3);
}
}

View File

@@ -0,0 +1,77 @@
package com.imyeyu.network;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.util.Timeout;
import java.io.IOException;
import java.io.InputStream;
/**
* @author 夜雨
* @since 2025-07-15 14:27
*/
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class CommonRequest {
protected final Request request;
public static CommonRequest wrap(Request request) {
return new CommonRequest(request);
}
public static CommonRequest get(String url) {
return new CommonRequest(Request.get(url));
}
public static CommonRequest post(String url) {
return new CommonRequest(Request.post(url));
}
public CommonRequest timeout(long ms) {
request.connectTimeout(Timeout.ofMilliseconds(ms)).responseTimeout(Timeout.ofMilliseconds(ms));
return this;
}
public CommonRequest header(String key, String value) {
request.addHeader(key, value);
return this;
}
public CommonRequest token(String token) {
request.addHeader("Token", token);
return this;
}
public CommonRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader);
return this;
}
public CommonRequest bodyEntity(HttpEntity entity) {
request.body(entity);
return this;
}
public String asString() throws IOException {
return request.execute().returnContent().asString();
}
public Number asNumber() throws IOException {
return Double.parseDouble(asString());
}
public byte[] asBytes() throws IOException {
return request.execute().returnContent().asBytes();
}
public InputStream asStream() throws IOException {
return request.execute().returnContent().asStream();
}
public void execute() throws IOException {
request.execute();
}
}

View File

@@ -0,0 +1,98 @@
package com.imyeyu.network;
import com.imyeyu.io.IO;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.ProtocolException;
import javax.naming.NoPermissionException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
/**
*
* @author 夜雨
* @since 2025-06-26 13:03
*/
public class FileRequest extends JacksonRequest {
protected FileRequest(Request request) {
super(request);
}
public static FileRequest wrap(Request request) {
return new FileRequest(request);
}
public static FileRequest get(String url) {
return new FileRequest(Request.get(url));
}
public static FileRequest post(String url) {
return new FileRequest(Request.post(url));
}
@Override
public FileRequest timeout(long ms) {
super.timeout(ms);
return this;
}
@Override
public FileRequest header(String key, String value) {
request.addHeader(key, value);
return this;
}
@Override
public FileRequest token(String token) {
request.addHeader("Token", token);
return this;
}
@Override
public FileRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader);
return this;
}
@Override
public FileRequest body(Object object) {
super.body(object);
return this;
}
@Override
public FileRequest bodyEntity(HttpEntity entity) {
super.bodyEntity(entity);
return this;
}
public void toFile(String path, String fileName) throws IOException, NoPermissionException {
toFile(new File(IO.fitPath(path) + fileName));
}
public void toFile(Path outputPath) throws IOException, NoPermissionException {
toFile(outputPath.toFile());
}
public void toFile(File file) throws IOException, NoPermissionException {
IO.toFile(file, asBytes());
}
public long length() throws IOException, ProtocolException {
HttpResponse response = request.execute().returnResponse();
final int status = response.getCode();
if (status < 200 || 300 <= status) {
throw new IOException("HTTP error status: " + status);
}
final Header contentLengthHeader = response.getHeader("Content-Length");
if (contentLengthHeader == null) {
throw new IOException("Content-Length header missing");
}
return Long.parseLong(contentLengthHeader.getValue());
}
}

View File

@@ -1,25 +0,0 @@
package com.imyeyu.network;
import org.apache.hc.client5.http.fluent.Form;
import org.apache.hc.core5.http.NameValuePair;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* HashMap 构建 {@link org.apache.hc.client5.http.fluent.Form} 参数列表
*
* @author 夜雨
* @since 2025-06-26 15:41
*/
public class FormMap<K, V> extends HashMap<K, V> {
public List<NameValuePair> build() {
Form form = Form.form();
for (Map.Entry<K, V> item : entrySet()) {
form.add(item.getKey().toString(), item.getValue().toString());
}
return form.build();
}
}

View File

@@ -0,0 +1,204 @@
package com.imyeyu.network;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import tools.jackson.core.JacksonException;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ArrayNode;
import tools.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* 基于 Jackson 的请求封装。
*
* @author 夜雨
* @since 2025-07-15 14:27
*/
public class JacksonRequest extends CommonRequest {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private ObjectMapper objectMapper = null;
protected JacksonRequest(Request request) {
super(request);
}
/**
* 获取当前请求使用的对象映射器。
*
* @return 对象映射器
*/
protected ObjectMapper getObjectMapper() {
if (objectMapper != null) {
return objectMapper;
}
return OBJECT_MAPPER;
}
/**
* 包装现有请求对象。
*
* @param request 请求对象
* @return Jackson 请求
*/
public static JacksonRequest wrap(Request request) {
return new JacksonRequest(request);
}
/**
* 创建 GET 请求。
*
* @param url 请求地址
* @return Jackson 请求
*/
public static JacksonRequest get(String url) {
return new JacksonRequest(Request.get(url));
}
/**
* 创建 POST 请求。
*
* @param url 请求地址
* @return Jackson 请求
*/
public static JacksonRequest post(String url) {
return new JacksonRequest(Request.post(url));
}
/**
* 指定对象映射器。
*
* @param objectMapper 对象映射器
* @return 当前请求
*/
public JacksonRequest objectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
@Override
public JacksonRequest timeout(long ms) {
super.timeout(ms);
return this;
}
@Override
public JacksonRequest header(String key, String value) {
request.addHeader(key, value);
return this;
}
@Override
public JacksonRequest token(String token) {
request.addHeader("Token", token);
return this;
}
@Override
public JacksonRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader);
return this;
}
/**
* 设置 JSON 请求体。
*
* @param object 要序列化的对象
* @return 当前请求
* @throws IllegalArgumentException JSON 序列化失败时抛出
*/
public JacksonRequest body(Object object) {
try {
request.bodyString(getObjectMapper().writeValueAsString(object), ContentType.APPLICATION_JSON);
return this;
} catch (JacksonException e) {
throw new IllegalArgumentException("Jackson serialize request body failed", e);
}
}
@Override
public JacksonRequest bodyEntity(HttpEntity entity) {
super.bodyEntity(entity);
return this;
}
/**
* 将响应体解析为指定类型。
*
* @param clazz 目标类型
* @param <T> 结果类型
* @return 解析结果
* @throws IOException 读取或解析失败
*/
public <T> T resultAs(Class<T> clazz) throws IOException {
return getObjectMapper().readValue(super.asString(), clazz);
}
/**
* 将响应体解析为指定泛型类型。
*
* @param typeReference 目标类型引用
* @param <T> 结果类型
* @return 解析结果
* @throws IOException 读取或解析失败
*/
public <T> T resultAs(TypeReference<T> typeReference) throws IOException {
return getObjectMapper().readValue(super.asString(), typeReference);
}
/**
* 将响应体解析为指定反射类型。
*
* @param type 目标类型
* @param <T> 结果类型
* @return 解析结果
* @throws IOException 读取或解析失败
*/
public <T> T resultAs(Type type) throws IOException {
return getObjectMapper().readValue(super.asString(), getObjectMapper().constructType(type));
}
/**
* 将响应体解析为 JSON 节点。
*
* @return JSON 节点
* @throws IOException 读取或解析失败
*/
public JsonNode asJsonNode() throws IOException {
return getObjectMapper().readTree(super.asString());
}
/**
* 将响应体解析为 JSON 对象。
*
* @return JSON 对象节点
* @throws IOException 读取或解析失败
*/
public ObjectNode asJsonObject() throws IOException {
JsonNode jsonNode = asJsonNode();
if (jsonNode instanceof ObjectNode objectNode) {
return objectNode;
}
throw new IOException("Response body is not a JSON object");
}
/**
* 将响应体解析为 JSON 数组。
*
* @return JSON 数组节点
* @throws IOException 读取或解析失败
*/
public ArrayNode asJsonArray() throws IOException {
JsonNode jsonNode = asJsonNode();
if (jsonNode instanceof ArrayNode arrayNode) {
return arrayNode;
}
throw new IOException("Response body is not a JSON array");
}
}

View File

@@ -32,7 +32,7 @@ public class Network {
dp.browse(URI.create(Encoder.url(url)));
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

View File

@@ -1,6 +1,7 @@
package com.imyeyu.network;
import com.imyeyu.io.IO;
import com.imyeyu.java.TimiJava;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.client5.http.fluent.Response;
import org.apache.hc.core5.http.HttpEntity;
@@ -9,6 +10,7 @@ import org.apache.hc.core5.http.io.entity.EntityUtils;
import javax.naming.NoPermissionException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
@@ -19,13 +21,12 @@ import java.nio.file.Path;
* @author 夜雨
* @since 2025-06-26 13:03
*/
public class ProgressiveRequest {
public class ProgressiveRequest extends FileRequest {
private final Request request;
private final ProgressiveCallback callback;
protected final ProgressiveCallback callback;
private ProgressiveRequest(Request request, ProgressiveCallback callback) {
this.request = request;
protected ProgressiveRequest(Request request, ProgressiveCallback callback) {
super(request);
this.callback = callback;
}
@@ -33,10 +34,66 @@ public class ProgressiveRequest {
return new ProgressiveRequest(request, callback);
}
public static ProgressiveRequest get(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.get(url), callback);
}
public static ProgressiveRequest post(String url, ProgressiveCallback callback) {
return new ProgressiveRequest(Request.post(url), callback);
}
@Override
public ProgressiveRequest timeout(long ms) {
super.timeout(ms);
return this;
}
@Override
public ProgressiveRequest header(String key, String value) {
request.addHeader(key, value);
return this;
}
@Override
public ProgressiveRequest token(String token) {
request.addHeader("Token", token);
return this;
}
@Override
public ProgressiveRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader);
return this;
}
@Override
public ProgressiveRequest body(Object object) {
super.body(object);
return this;
}
@Override
public ProgressiveRequest bodyEntity(HttpEntity entity) {
super.bodyEntity(entity);
return this;
}
@Override
public void toFile(Path outputPath) throws IOException, NoPermissionException {
processResponse(request.execute(), IO.getOutputStream(outputPath.toFile()));
}
@Override
public void toFile(File file) throws IOException, NoPermissionException {
processResponse(request.execute(), IO.getOutputStream(file));
}
@Override
public String asString() throws IOException {
return new String(asBytes());
}
@Override
public byte[] asBytes() throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
processResponse(request.execute(), os);
@@ -55,6 +112,9 @@ public class ProgressiveRequest {
}
long length = entity.getContentLength();
if (TimiJava.isEmpty(callback)) {
IO.toOutputStream(entity.getContent(), os);
} else {
IO.toOutputStream(entity.getContent(), os, new IO.OnWriteCallback() {
@Override
@@ -63,6 +123,7 @@ public class ProgressiveRequest {
return callback.handler(length, total, now);
}
});
}
EntityUtils.consume(entity);
return null;
});

View File

@@ -0,0 +1,165 @@
package com.imyeyu.network;
import com.imyeyu.java.bean.timi.TimiResponse;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpEntity;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.JavaType;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* @author 夜雨
* @since 2025-07-15 14:34
*/
public class TimiRequest extends JacksonRequest {
protected TimiRequest(Request request) {
super(request);
}
public static TimiRequest wrap(Request request) {
return new TimiRequest(request);
}
public static TimiRequest get(String url) {
return new TimiRequest(Request.get(url));
}
public static TimiRequest post(String url) {
return new TimiRequest(Request.post(url));
}
@Override
public TimiRequest timeout(long ms) {
super.timeout(ms);
return this;
}
@Override
public TimiRequest header(String key, String value) {
request.addHeader(key, value);
return this;
}
@Override
public TimiRequest token(String token) {
request.addHeader("Token", token);
return this;
}
@Override
public TimiRequest language(String langHeader) {
request.addHeader("Accept-Language", langHeader);
return this;
}
@Override
public TimiRequest body(Object object) {
super.body(object);
return this;
}
@Override
public TimiRequest bodyEntity(HttpEntity entity) {
super.bodyEntity(entity);
return this;
}
@Override
public String asString() throws IOException {
return resultAs(String.class);
}
@Override
public Number asNumber() throws IOException {
return Double.parseDouble(asString());
}
/**
* 读取 Timi 响应中的数据字段。
*
* @param clazz 数据类型
* @param <T> 数据泛型
* @return 数据内容
* @throws IOException 读取或解析失败
*/
public <T> T resultAs(Class<T> clazz) throws IOException {
TimiResponse<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(clazz));
if (resp.isFail()) {
throw resp.toException();
}
return resp.getData();
}
/**
* 读取 Timi 响应中的泛型数据字段。
*
* @param typeReference 数据类型引用
* @param <T> 数据泛型
* @return 数据内容
* @throws IOException 读取或解析失败
*/
public <T> T resultAs(TypeReference<T> typeReference) throws IOException {
TimiResponse<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(typeReference));
if (resp.isFail()) {
throw resp.toException();
}
return resp.getData();
}
/**
* 读取 Timi 响应中的泛型数据字段。
*
* @param type 数据类型
* @param <T> 数据泛型
* @return 数据内容
* @throws IOException 读取或解析失败
*/
public <T> T resultAs(Type type) throws IOException {
TimiResponse<T> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(type));
if (resp.isFail()) {
throw resp.toException();
}
return resp.getData();
}
@Override
public void execute() throws IOException {
TimiResponse<?> resp = getObjectMapper().treeToValue(asJsonObject(), timiResponseType(Object.class));
if (resp.isFail()) {
throw resp.toException();
}
}
/**
* 构造带泛型的 Timi 响应类型。
*
* @param clazz 数据类型
* @return Jackson 类型
*/
protected JavaType timiResponseType(Class<?> clazz) {
return getObjectMapper().getTypeFactory().constructParametricType(TimiResponse.class, clazz);
}
/**
* 构造带泛型的 Timi 响应类型。
*
* @param typeReference 数据类型引用
* @return Jackson 类型
*/
protected JavaType timiResponseType(TypeReference<?> typeReference) {
return getObjectMapper().getTypeFactory().constructParametricType(TimiResponse.class, getObjectMapper().constructType(typeReference));
}
/**
* 构造带泛型的 Timi 响应类型。
*
* @param type 数据类型
* @return Jackson 类型
*/
protected JavaType timiResponseType(Type type) {
return getObjectMapper().getTypeFactory().constructParametricType(TimiResponse.class, getObjectMapper().constructType(type));
}
}

View File

@@ -0,0 +1,36 @@
package com.imyeyu.network.test;
import com.imyeyu.network.ArgMap;
import org.junit.Test;
/**
*
*
* @author 夜雨
* @since 2026-02-10 12:45
*/
public class ArgMapTest {
@Test
public void toURLTest() {
assert ArgMap.of("key", "value").toURL("/detail").equals("/detail?key=value");
assert ArgMap.of("key", "value").toURL("/detail?").equals("/detail?key=value");
assert ArgMap.of("key", "value").toURL("/detail?id=123").equals("/detail?id=123&key=value");
assert ArgMap.of("key", "value").toURL("/detail?id=123&").equals("/detail?id=123&key=value");
assert ArgMap.of("key", "value").toURL("http://localhost/detail").equals("http://localhost/detail?key=value");
assert ArgMap.of("key", "value").toURL("http://localhost/detail?").equals("http://localhost/detail?key=value");
String uri = ArgMap.of("key", "value").toURL("/detail?id=123");
String url = ArgMap.of("newKey", "newValue").toURL("http://localhost/test" + uri);
assert url.equals("http://localhost/test/detail?id=123&key=value&newKey=newValue");
}
@Test
public void duplicateKeyTest() {
ArgMap<String, String> argMap = new ArgMap<>();
argMap.put("id", "1");
argMap.put("id", "2");
assert argMap.toURL().equals("id=1&id=2");
assert argMap.toURL("/detail").equals("/detail?id=1&id=2");
}
}

View File

@@ -0,0 +1,41 @@
package com.imyeyu.network.test;
import com.imyeyu.io.IOSize;
import com.imyeyu.network.FileRequest;
import com.imyeyu.network.ProgressiveRequest;
import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpResponse;
import org.junit.Test;
/**
* @author 夜雨
* @since 2025-07-14 15:30
*/
public class ProgressRequestTest {
private static final String URL1 = "http://localhost:8091/system/file/download/video/test92MB.mp4?key=GS60MF78GbPhImiCN4fsi3T2E5tDfP1scxufVhbuccaxldba0okpQPgKq4ntyr0J";
private static final String URL2 = "https://git.imyeyu.com/test92MB.mp4";
private static final String URL3 = "http://localhost:8092/test/download";
@Test
public void testGet() throws Exception {
ProgressiveRequest.get(URL1, (total, read, now) -> {
System.out.println(1D * read / total);
return true;
}).asBytes();
}
@Test
public void testLength() throws Exception {
long length = FileRequest.wrap(Request.head(URL2)).length();
System.out.println(IOSize.format(length));
}
@Test
public void testLength2() throws Exception {
HttpResponse response = Request.head(URL3).execute().returnResponse();
final Header contentLengthHeader = response.getHeader("Content-Length");
System.out.println(contentLengthHeader.getValue());
}
}