okhttp3图片压缩上传

编程入门 行业动态 更新时间:2024-10-07 20:32:26

okhttp3图片压缩<a href=https://www.elefans.com/category/jswz/34/1771255.html style=上传"/>

okhttp3图片压缩上传

我知道

okhttp3

库默认情况下,它添加头

Accept-Encoding: gzip

为我们自动解码。

我要处理的问题是,一个主机只接受这样的头:

Accept-Encoding: gzip, deflate

如果我不加上

deflate

部分失败。现在,当我手动将该头添加到okhttp客户端时,库不再为我执行解压。

我尝试了多种解决方案来获取响应并尝试手动解压缩,但我总是以一个例外而告终,即。

java.util.zip.ZipException: Not in GZIP format

,以下是我迄今为止所做的尝试:

//decompresser

public static String decompressGZIP(InputStream inputStream) throws IOException

{

InputStream bodyStream = new GZIPInputStream(inputStream);

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[4096];

int length;

while ((length = bodyStream.read(buffer)) > 0)

{

outStream.write(buffer, 0, length);

}

return new String(outStream.toByteArray());

}

//run scraper

scrape(api, new Callback()

{

// Something went wrong

@Override

public void onFailure(@NonNull Call call, @NonNull IOException e)

{

}

@Override

public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException

{

if (response.isSuccessful())

{

try

{

InputStream responseBodyBytes = responseBody.byteStream();

returnedObject = GZIPCompression.decompress(responseBodyBytes);

if (returnedObject != null)

{

String htmlResponse = returnedObject.toString();

}

}

catch (ProtocolException e){}

if(response != null) response.close();

}

}

});

private Call scrape(Map, ?> api, Callback callback)

{

MediaType JSON = MediaType.parse("application/json; charset=utf-8");

String method = (String) api.get("method");

String url = (String) api.get("url");

Request.Builder requestBuilder = new Request.Builder().url(url);

RequestBody requestBody;

requestBuilder.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");

requestBuilder.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

requestBuilder.header("Accept-Language", "en-US,en;q=0.5");

requestBuilder.header("Accept-Encoding", "gzip, deflate");

requestBuilder.header("Connection", "keep-alive");

requestBuilder.header("Upgrade-Insecure-Requests", "1");

requestBuilder.header("Cache-Control", "max-age=0");

Request request = requestBuilder.build();

Call call = client.newCall(request);

call.enqueue(callback);

return call;

}

Content-Encoding: gzip

Transfer-Encoding: chunked

还有一件事,我也试过

this topic

但还是失败了

D/OkHttp: java.io.IOException: ID1ID2: actual 0x00003c68 != expected 0x00001f8b

.

更多推荐

okhttp3图片压缩上传

本文发布于:2024-02-28 08:32:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1768786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传   图片

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!