[Java] Fix java.io.IOException: Server returned HTTP response code: 403 for URL … on production

Mình bị lỗi này khi download 1 ảnh trên môi trường production sử dụng url.openStream()

Mặc dù khi mở từ browser thì link ảnh đó vẫn hoạt động bình thường.

Nguyên nhân là không có User-Agent.

Sau đó mình thay đổi cách lấy ảnh, sử dụng HttpURLConnection để set thuộc tính User-Agent ở đó.

URL urlImage = new URL(strUrlImage);// strUrlImage là link ảnh của bạn
// fix : java.io.IOException: Server returned HTTP response code: 403 for URL
HttpURLConnection httpURLConnection = (HttpURLConnection) urlImage.openConnection();
httpURLConnection.addRequestProperty("User-Agent", "Mozilla/4.0");

BufferedImage bodyAnimalImage = ImageIO.read(httpURLConnection.getInputStream());

Vậy là hết lỗi 403 rồi. Bạn thử xem được không nhé 😉