Files
timi-network/src/main/java/com/imyeyu/network/FileRequest.java
Timi ada0f96e57
All checks were successful
CI/CD / build-deploy (pull_request) Successful in 3m4s
v0.0.5
2026-03-16 17:13:10 +08:00

99 lines
2.3 KiB
Java

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());
}
}