Missing Bottom part of image using getResponse().g

2019-09-09 02:49发布

问题:

i got the image from post response

PostMethod post = new PostMethod(action);
HttpClient httpClient = createHttpClient();

........

httpClient.executeMethod(post);


try {
            log.info("post successfully");
            String contentType = post.getResponseHeader("Content-type").getValue();
            int contentLength = (int) post.getResponseContentLength();
            byte[] responseBody = FileUtils.convertInputStreamtoByteArray(post.getResponseBodyAsStream());
            log.info("get response sucessfully : size "+ responseBody.length +" contentLength " + contentLength);
            return new ReturnBean(null, responseBody,contentType,contentLength);
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error(e.getStackTrace());
            e.printStackTrace();
            throw new ResponseFailedException(e.getMessage());
        }

this is how i convert inputstream to byte array.

public static byte[] convertInputStreamtoByteArray(InputStream is){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = is.read(buf)) >= 0) {
                baos.write(buf, 0, i);
            }
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return baos.toByteArray();
    }

this is how i return the image as a response.

byte[] imageSource = (byte[])returnStream.getBean();
            log.info("imageSource " + imageSource.length);
            getResponse().setContentType((String) returnStream.getBean2());
            getResponse().setContentLength((Integer) returnStream.getBean3());
            getResponse().getOutputStream().write(imageSource);
            getResponse().getOutputStream().flush();

i was able to print out the image but im having a problem because the bottom part of it is missing . i checked the size of byte that i got and it is equal to the size of actual image.

回答1:

when i used IOUtils.copyLarge(); instead of my method convertInputStreamtoByteArray

ServletOutputStream outputStream = getResponse().getOutputStream();
            InputStream inputStream = (InputStream) returnStream.getBean();
            IOUtils.copyLarge(inputStream , outputStream);

it works . i dont know what happen because i used it a while ago and it didnt work.