Olá pessoal,
Estou tentando fazer um código em java aonde eu acesso um endereço url capturo o html da página e envio para o banco de dados.
Até o momento eu consegui acessar a url e imprimir o html no console, mas não estou conseguindo salvar no banco de dados.
Abaixo o código.
Classe App.java
package br.com.partnergroup.robo.test.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import br.com.partnergroup.robo.test.bd.H2Server;
public class App {
public void getPage(URL urlSite) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(urlSite.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
// Imprime página no console
System.out.println(inputLine);
}
in.close();
}
public static void main(String[] args) throws SQLException, Exception {
URL urlSite = null;
urlSite = new URL("https://www.msn.com/pt-br/?ocid=mailsignout");
new App().getPage(urlSite);
String url = "jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
String sql = "insert into tb_html (html) values (?)";
try (Connection con = DriverManager.getConnection(url, "sa", "")) {
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, urlSite.getFile());
stmt.execute();
try (H2Server server = new H2Server()) {
server.start();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Clique em ok para finalizar");
}
}
}
Classe H2Server.java
package br.com.partnergroup.robo.test.bd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.tools.Server;
public class H2Server extends Thread implements AutoCloseable {
private Server server;
public H2Server() throws SQLException {
super();
}
@Override
public void run() {
super.run();
try {
server=Server.createWebServer("-webDaemon","-webPort","9099");
server.start();
criarTabelas();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void criarTabelas() throws SQLException {
String url="jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1";
try(Connection con = DriverManager.getConnection(url,"sa","")){
try(PreparedStatement ps = con.prepareStatement("CREATE TABLE if not exists tb_html(id INT PRIMARY KEY auto_increment, html varchar);")){
ps.execute();
}
}
}
public void close() throws Exception {
server.stop();
interrupt();
}
}