下面的代码用于读取API中的数据。来自API的数据流采用gzip编码。当单个API被击中时,数据就会正确出现,但是当使用多线程同时命中少量API(不同的API)时,它就会在下面的代码中的reader.readLine()行抛出异常。
所用JDK : 1.8
异常
java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240) ~?:1.8.0_191中ZLIB输入流的意外结束
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection != null) {
//encoding
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(0);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlResponseCode = urlConnection.getResponseCode();
if (urlResponseCode == HttpURLConnection.HTTP_OK) {
inputStream = urlConnection.getInputStream();
if (inputStream != null) {
if ("gzip".equalsIgnoreCase(urlConnection.getContentEncoding())) {
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(inputStream)));
} else {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
String line;
long mb = 1024 * 1024;
while ((line = reader.readLine()) != null) {
//adding the line to a String Builder
}
我知道有一些基于这个异常的堆叠溢出文章,但它们是在不同的情况下出现的。所以,我问过这个问题。
我也知道,异常是可以捕捉到的&向前推进。但这可能会导致数据丢失。因此,如果提供替代方法,情况会更好。
这一例外的原因是什么?
发布于 2021-04-28 20:17:39
我也知道异常是可以捕捉到的&向前移动。但这可能会导致数据丢失。因此,如果提供替代方法,情况会更好。
除非我搞错了,否则在客户端你什么也做不了。
问题是客户端代码正在读取的输入流已被截断。
它可以是:
服务器中的
flush()
是不够的。GZIPOutputStream
本身必须关闭..。假设压缩数据流是这样的,generated.)服务器也有可能“放弃”请求,因为客户端读取请求太慢,或者遇到错误。这两种情况都可能是由于客户机(或客户端)将请求重载服务器造成的。但是如果是这样的话,解决方案仍然必须在服务器端;例如,减少服务器端工作线程的数量,以便服务器更好地处理重载。
https://stackoverflow.com/questions/67310811
复制