使用okhttp分片上传文件,报错:java.net.SocketException: Broken pipe,java.net.ProtocolException: unexpected end of stream

private void UploadFile(String id, String name, long chunkSize, long size, Uri uri) {
CHUNK_SIZE = chunkSize;
OkHttpClient client = new OkHttpClient().newBuilder()
.callTimeout(3000, TimeUnit.MILLISECONDS)
.connectTimeout(3000, TimeUnit.MILLISECONDS)
.readTimeout(3000, TimeUnit.MILLISECONDS).build();
ContentResolver contentResolver = requireActivity().getContentResolver();
try {
InputStream inputStream = contentResolver.openInputStream(uri);
if (inputStream == null) {
throw new IOException("Failed to open input stream for URI: " + uri);
}
long fileSize = contentResolver.openFileDescriptor(uri, "r").getStatSize();
long offset = 0;
int chunkIndex = 0; // 分片编号从0开始
while (offset < fileSize) {
long chunk_Size = Math.min(CHUNK_SIZE, fileSize - offset);
RequestBody requestBody = new ChunkedRequestBody(inputStream, offset, (int) chunk_Size);
String uploadUrl = NasUrl.FILE_UPLOAD + "/" + id + "/" + chunkIndex; // 构建上传URL
Log.e(TAG, "UploadFile: 分片大小:" + chunk_Size);
Log.e(TAG, "UploadFile: 请求地址:" + uploadUrl);
Request request = new Request.Builder()
.url(uploadUrl)
.method("POST", requestBody)
.header("Accept", "application/json, text/plain, */*")
.header("content-type", "application/octet-stream")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.e(TAG, "UploadFile: 请求后:" + e);
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
Log.e(TAG, "UploadFile: 后台返回:" + response.body().string());
}
});
// try (Response response = client.newCall(request).execute()) {
// if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Log.d("Upload", response.body().string());
// }
offset += chunk_Size;
chunkIndex++; // 准备上传下一个分片
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class ChunkedRequestBody extends RequestBody {
private final InputStream inputStream;
private final long offset;
private final int byteCount;
ChunkedRequestBody(InputStream inputStream, long offset, int byteCount) {
this.inputStream = inputStream;
this.offset = offset;
this.byteCount = byteCount;
}
@Override
public MediaType contentType() {
return MediaType.parse("application/octet-stream");
}
@Override
public long contentLength() {
return byteCount;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
inputStream.skip(offset);
byte[] buffer = new byte[8192];
int bytesRead;
long bytesRemaining = byteCount;
while (bytesRemaining > 0 && (bytesRead = inputStream.read(buffer, 0, (int) Math.min(buffer.length, bytesRemaining))) != -1) {
sink.write(buffer, 0, bytesRead);
bytesRemaining -= bytesRead;
}
}
}