Если вы сначала вызываете URL.openConnection и приводите его к HttpURLConnection, то вы можете проверить состояние и прочитать текст ошибки, используя getErrorStream (), и вызвать исключение, содержащее сообщение об ошибке.
Просто замените код для этогоМетод:
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
if (conn.getResponseCode() != 200) {
// error occurred, get details and throw exception
// this uses Commons IO to read all bytes from an InputStream
byte[] errorBytes = IOUtils.readFully(conn.getErrorStream(), 2048, false);
// if you have Java 9+ then use this instead:
// byte[] errorBytes = conn.getErrorStream().readFully();
String msg = new String(errorBytes, "UTF-8");
throw new IOException(msg);
}
InputStream is = conn.getInputStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}