gpt4 book ai didi

java - 使用 okhttp 上传文件时出现奇怪的数据包

转载 作者:行者123 更新时间:2023-11-30 11:13:10 24 4
gpt4 key购买 nike

我正在尝试通过 okhttp 将文件上传到服务器,我正在使用一个表单,因此使用了 MultipartBuilder。

OkHttpClient client = new OkHttpClient();
MediaType OCTET_STREAM = MediaType.parse("application/octet-stream");
RequestBody body = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(Headers.of("Content-Disposition",
"form-data; name=\"breadcrumb\"; filename=\"myfile.bin\"",
"Content-Transfer-Encoding", "binary"),
RequestBody.create(OCTET_STREAM, file))
.build();

Request request = new Request.Builder()
.header("Authorization", cred)
.url(url)
.post(body)
.build();

Response response = client.newCall(request).execute();

但是在追踪线路上发生的事情时:

POST /breadcrumb/ HTTP/1.1
Authorization: Basic aHl6OmhvbGExMjM=
Content-Type: multipart/form-data; boundary=9bc835d6-24b8-42c4-ae8d-5bc89b3fe68f
Transfer-Encoding: chunked
Host: myurl:8000
Connection: Keep-Alive
Accept-Encoding: gzip

10e
--9bc835d6-24b8-42c4-ae8d-5bc89b3fe68f
Content-Disposition: form-data; name="breadcrumb"; filename="myfile.bin"
Content-Transfer-Encoding: binary
Content-Type: application/octet-stream
Content-Length: 21

some file content in binary

--9bc835d6-24b8-42c4-ae8d-5bc89b3fe68f--
0

当我使用传统的 Apache http 构建器时,它看起来很相似,但我没有看到开头和结尾的奇怪字符 (10e, 0)。有什么想法吗?

感谢您的帮助。

最佳答案

您没有指定确切的 Content-Length header ,因此 OkHttpClient 开始使用分块传输编码。

在 HTTP 协议(protocol)中,接收方必须始终知道内容的确切长度(用于分配内存或其他资源),然后内容才会真正发送到服务器。有两种发送方式 - Content-Length header 中的整个内容长度,或者如果在请求开始时无法计算内容长度,则使用 chucked 编码。

这一行:

10e

只是说在那行之后客户端将发送一些长度为 0x10e (270) 字节的数据的一部分。

关于java - 使用 okhttp 上传文件时出现奇怪的数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26522412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com