您好,登录后才能下订单哦!
这篇文章主要讲解了“CloseableHttpClient出现Premature end of Content-Length delimited message body怎么解决”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“CloseableHttpClient出现Premature end of Content-Length delimited message body怎么解决”吧!
一、问题描述
今天在用CloseableHttpClient请求服务器获取图片流,获取之后转换成字节数组,出现以下异常:
原代码如下:
public static byte[] getPic(String urlPath){ try { InputStream inStream=null; /** * *方法二 HttpClient*/ CloseableHttpClient client= HttpClients.createDefault(); HttpGet method=new HttpGet(urlPath);//获取内容用GetMethod,经过测试PostMethod拿不到图片的内容 // RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(DEFAULT_CONNECT_TIMEOUT) // .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT) // .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build(); // method.setConfig(requestConfig); CloseableHttpResponse response = client.execute(method); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ byte[] btImg = EntityUtils.toByteArray(response.getEntity()); return btImg; }else{ log.error("网络异常"); } } catch (Exception e) { log.error("下载失败"); e.printStackTrace(); } return null; } private static byte[] readStream(InputStream inStream) throws IOException { byte[] b = new byte[1024]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int l = -1; while((l = inStream.read(b)) > -1){ os.write(b, 0, l);; } os.flush(); b = os.toByteArray(); os.close(); return b; }
二、解决问题
后来将CloseableHttpClient替换成了低版本的HttpClient,问题就解决了,暂时还不知道原因。
修改后的代码如下:
public static byte[] getPic(String urlPath){ try { InputStream inStream=null; /** * *方法二 HttpClient*/ HttpClient client=new HttpClient(); GetMethod method = new GetMethod(urlPath);//获取内容用GetMethod,经过测试PostMethod拿不到图片的内容 int status=client.executeMethod(method); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); //设置编码 if(status==HttpStatus.SC_OK){ inStream=method.getResponseBodyAsStream(); //long a=System.currentTimeMillis(); byte[] btImg = readStream(inStream);//得到图片的二进制数据 //long b=System.currentTimeMillis(); //System.out.println("转化为流耗时:"+(b-a)); return btImg; }else{ log.error("网络异常"); } } catch (Exception e) { log.error("下载失败"); e.printStackTrace(); } return null; } private static byte[] readStream(InputStream inStream) throws IOException { byte[] b = new byte[1024]; ByteArrayOutputStream os = new ByteArrayOutputStream(); int l = -1; while((l = inStream.read(b)) > -1){ os.write(b, 0, l);; } os.flush(); b = os.toByteArray(); os.close(); return b; }
感谢各位的阅读,以上就是“CloseableHttpClient出现Premature end of Content-Length delimited message body怎么解决”的内容了,经过本文的学习后,相信大家对CloseableHttpClient出现Premature end of Content-Length delimited message body怎么解决这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。