Hello, I have a system that reads XML files, transforms into JSON and makes HTTP (POST) requests to another server to save the data in the database. However some XML files have, for example, null fields that the server does not allow to save without, and then the server returns the exception. This is my connection class with the server:
public class Conexao {
public void sendPost(String json, URL url) throws Exception {
try {
// Cria um objeto HttpURLConnection:;
HttpURLConnection request = (HttpURLConnection)
url.openConnection();
try {
// Define que a conexão pode enviar informações e obtê-las de volta:
request.setDoOutput(true);
request.setDoInput(true);
// Define o content-type:
request.setRequestProperty("Content-Type", "application/json");
// Define o método da requisição:
request.setRequestMethod("POST");
// Conecta na URL:
request.connect();
// Escreve o objeto JSON usando o OutputStream da requisição:
try (OutputStream outputStream = new BufferedOutputStream(request.getOutputStream())) {
outputStream.write(json.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
}
int response = request.getResponseCode();
BufferedReader br;
if (200 <= response && response <= 299) {
//Requisição feita com sucesso
} else {
br = new BufferedReader(new InputStreamReader((request.getErrorStream())));
String resul = br.readLine();
throw new Exception(" Dados da requisição: " + resul);
}
}
} finally {
request.disconnect();
}
} catch (Exception e) {
throw (e);
}
}
}
Until then, however, I need to capture these exceptions and show on my system why the file did not save in the database. When I run this function and the error on the server, "resul" returns me to the server's HTML, full of unnecessary information and most of the time without the error caused. Can anyone tell me if it is possible to just catch the exception caused by the HttpURLConnection response?