我正在访问一个外部api,并且希望得到一个图像作为响应(apply plugin: 'com.android.library'
)。我连接到此端点的方法如下:
byte[]
原来,如果我将错误的参数传递给目标端点,则会收到以下错误消息:
因此,基本上,我想 private byte[] retrieveImage(String uri) {
byte[] imageBytes = null;
try {
URL url = new URL(uri);
BufferedImage bufferedImage = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
imageBytes = baos.toByteArray();
} catch (Exception ex) {
throw new ImageNotReadException(ex.getLocalizedMessage());
}
return imageBytes;
}
与上面的错误相同,但我也想throw
和一个throw
(ImageNotReadException
),以防程序无法读取图片(java.lang.IllegalArgumentException: image == null!
)。因此,基本上,我的方法byte[]
必须抛出读取图像异常和端点响应异常。
有什么提示吗? 感谢帮助!
答案 0 :(得分:1)
我已评论,请参阅以下选项
private Response retrieveImage(String uri) {
byte[] imageBytes = null;
Response r=new Response();
try {
URL url = new URL(uri);
BufferedImage bufferedImage = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
imageBytes = baos.toByteArray();
r.setImage(imageBytes);
r.setStatus(1);
} catch (Exception ex) {
r.setStatus(0);
}
return r;
}
响应:
class Response{
String status;
byte[] image;
//getters setters
}
或:
private Response retrieveImage(String uri)throws CustomException {
byte[] imageBytes = null;
try {
URL url = new URL(uri);
BufferedImage bufferedImage = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
imageBytes = baos.toByteArray();
} catch (Exception ex) {
throw new CustomException(ex.getLocalizedMessage());
}
return imageBytes;
}