Java获取网络文件并插入数据库的代码

获取百度的歌曲名,歌手和链接!!


代码如下:

package webTools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import dbTools.DBTools;
public class IOTOWeb {
public String getHtmlContent(String htmlURL) {
URL url = null;
String rowContent = "";
StringBuffer htmlContent = new StringBuffer();
try {
url = new URL(htmlURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url
.openStream(), "gb2312"));
while ((rowContent = in.readLine()) != null) {
htmlContent.append(rowContent);
}
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return htmlContent.toString();
}
public List getLink(String htmlContent) {
ArrayList listLink = new ArrayList();
String regex = "<td[^>]*>[\\(]*<a[^>]*href=(\"([^\"]*)\"|\'([^\']*)\'|([^\\s>]*))[^>]*>(.*?)[\\)]*[\\s]*</td>";
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(htmlContent);
while (matcher.find()) {
listLink.add(matcher.group());
}
return listLink;
}
public List<String> getHref(String htmlContent) {
String regex;
List listtHref = new ArrayList();
regex = "href=(\"([^\"]*)\"|\'([^\']*)\'|([^\\s>]*))\"";
Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
Matcher ma = pa.matcher(htmlContent);
while (ma.find()) {
listtHref.add(ma.group().replaceFirst("href=\"", "").replace("\"",
""));
}
return listtHref;
}
public List<String> getPerson(String htmlContent) {
String regex;
List list = new ArrayList();
regex = "\\(<a[^>]*href=(\"([^\"]*)\"|\'([^\']*)\'|([^\\s>]*))[^>]*>(.*?)\\)";
Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
Matcher ma = pa.matcher(htmlContent);
while (ma.find()) {
list.add(ma.group().replaceFirst("href=\"", "").replace("\"", ""));
}
return list;
}
public List<String> getSongName(String htmlContent) {
String regex;
List listPerson = new ArrayList();
regex = "<a[^>]*href=(\"([^\"]*)\"|\'([^\']*)\'|([^\\s>]*))[^>]*>(.*?)</a>\\s";
Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
Matcher ma = pa.matcher(htmlContent);
while (ma.find()) {
listPerson.add(ma.group());
}
return listPerson;
}
public String getMainContent(String htmlContent) {
String regex = "<table width=\"100%\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" class=\"list\">(.*?)</table>";
StringBuffer mainContent = new StringBuffer();
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(htmlContent);
while (matcher.find()) {
mainContent.append(matcher.group());
}
return mainContent.toString();
}
public String outTag(final String s) {
return s.replaceAll("<.*?>", "");
}
DBTools dbTools = new DBTools();
public void getFromBaiduMap3(String htmlURL) throws Throwable {
HashMap htmlContentMap = new HashMap();
String htmlContent = getHtmlContent(htmlURL);
String mainContent = getMainContent(htmlContent);
List listLink = getLink(mainContent);
for (int j = 0; j < listLink.size(); j++) {
String tdTag = listLink.get(j).toString();
List songNameList = getSongName(tdTag);
String songName = outTag(songNameList.get(0).toString());
List personList = getPerson(tdTag);
String songPerson = "";
if (personList.size() != 0) {
for (int n = 0; n < personList.size(); n++) {
// System.out.println(personList.get(n).toString());
songPerson = outTag(personList.get(n).toString());
}
} else {
songPerson = "无";
}
// System.out.print(songNameList.get(0).toString());
List hrefList = getHref(songNameList.get(0).toString());
String songHref = hrefList.get(0).toString();
System.out.println();
String sql = "insert into song(songName,songPerson,songHref) values(?,?,?)";
ArrayList list_values = new ArrayList();
list_values.add(songName);
list_values.add(songPerson);
list_values.add(songHref);
dbTools.update(sql, list_values);
}
}
}

DBTools数据库链接类:


代码如下:

package dbTools;
import java.util.ArrayList;
import java.sql.*;
public class DBTools {
private PreparedStatement preparedStatement;
private ResultSet resultSet;
private Connection connection;
public DBTools() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/TestURL", "root", "zhuyi");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList query(String sql, ArrayList list_values) throws Throwable {
ArrayList listRows = new ArrayList();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < list_values.size(); i++) {
preparedStatement.setObject(i + 1, list_values.get(i));
}
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String[] rowinfo = new String[resultSet.getMetaData()
.getColumnCount()];
for (int i = 0; i < rowinfo.length; i++) {
rowinfo[i] = resultSet.getString(i + 1);
}
listRows.add(rowinfo);
}
return listRows;
}
public void update(String sql, ArrayList list_values) throws Throwable {
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < list_values.size(); i++) {
preparedStatement.setObject(i + 1, list_values.get(i));
}
preparedStatement.executeUpdate();
preparedStatement.close();
}
}

Servlet调用:


代码如下:

package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webTools.IOTOWeb;
public class TestURL extends HttpServlet {
/**
* Constructor of the object.
*/
public TestURL() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
IOTOWeb iotoWeb = new IOTOWeb();
iotoWeb.getFromBaiduMap3("http://list.mp3.baidu.com/topso/mp3topsong.html?id=1?top2");
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}

获取金书网的图书名:


代码如下:

package webTools;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import dbTools.DBTools;
public class GetBook {
public String getHtmlContent(String htmlURL) throws Throwable {
URL url = null;
String rowContent = "";
StringBuffer htmlContent = new StringBuffer();
url = new URL(htmlURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url
.openStream(), "gb2312"));
while ((rowContent = in.readLine()) != null) {
htmlContent.append(rowContent);
}
in.close();
return htmlContent.toString();
}
public String getBookName(String htmlContent) {
String bookName = "";
String regex = "<span class=\"style15\">[^>]*</span>";
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(htmlContent);
if (matcher.find()) {
bookName = matcher.group();
}
return bookName;
}
public String outTag(final String s) {
return s.replaceAll("<.*?>", "");
}
DBTools dbtools = new DBTools();
public void getFromJINSHU(String htmlURL) throws Throwable {
String htmlContent = getHtmlContent(htmlURL);
String bookName = outTag(getBookName(htmlContent));
if (bookName != null && !"".equals(bookName)) {
System.out.println(bookName);
String sql = "insert into bookinfo(bookName) values(?)";
ArrayList list_values = new ArrayList();
list_values.add(bookName);
dbtools.update(sql, list_values);
}
}
}

调用Servlet:


代码如下:

package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import webTools.GetBook;
public class TestBook extends HttpServlet {
/**
* Constructor of the object.
*/
public TestBook() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
int i = 1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
GetBook bookinfo = new GetBook();
for (; i < 10000; i++) {
String bookURL = "http://www.golden-book.com/booksinfo/12/" + i
+ ".html";
try {
bookinfo.getFromJINSHU(bookURL);
} catch (Throwable e) {
i++;
doPost(request, response);
}
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
GetBook bookinfo = new GetBook();
for (; i < 10000; i++) {
String bookURL = "http://www.golden-book.com/booksinfo/12/" + i
+ ".html";
try {
bookinfo.getFromJINSHU(bookURL);
} catch (Throwable e) {
i++;
doGet(request, response);
}
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}

每种功能的实现方法有很多,希望各位可以交流不同的思想和方法。可以加QQ412546724。呵呵

(0)

相关推荐

  • Powershell实现监测服务器连通状态

    工作中可能会遇到有几台托管的服务器,比如数据库,一旦网络中断就会影响到数据采集. 为此你可以使用下面脚本,它用计划任务每小时执行一次,一旦服务器出现断网,则会弹出提示窗口,代码如下: 复制代码 代码如下: $computerNames = @("10.3.X.56","10.0.XX.123")  $computerNames|%{     if(!(Test-Connection -ComputerName $_ -Quiet )){         cmd /c

  • Java实现爬虫给App提供数据(Jsoup 网络爬虫)

    一.需求 最近基于 Material Design 重构了自己的新闻 App,数据来源是个问题. 有前人分析了知乎日报.凤凰新闻等 API,根据相应的 URL 可以获取新闻的 JSON 数据.为了锻炼写代码能力,笔者打算爬虫新闻页面,自己获取数据构建 API. 二.效果图 下图是原网站的页面 爬虫获取了数据,展示到 APP 手机端 三.爬虫思路 关于App 的实现过程可以参看这几篇文章,本文主要讲解一下如何爬虫数据. Android下录制App操作生成Gif动态图的全过程 :http://www

  • 简单介绍Java网络编程中的HTTP请求

    HTTP请求的细节--请求行   请求行中的GET称之为请求方式,请求方式有:POST.GET.HEAD.OPTIONS.DELETE.TRACE.PUT,常用的有: GET. POST 用户如果没有设置,默认情况下浏览器向服务器发送的都是get请求,例如在浏览器直接输地址访问,点超链接访问等都是get,用户如想把请求方式改为post,可通过更改表单的提交方式实现. 不管POST或GET,都用于向服务器请求某个WEB资源,这两种方式的区别主要表现在数据传递上:如果请求方式为GET方式,则可以在请

  • java网络编程中向指定URL发送GET POST请求示例

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import jav

  • Java网络编程基础教程之Socket入门实例

    当我们想要在Java中使用TCP/IP通过网络连接到服务器时,就需要创建java.net.Socket对象并连接到服务器.假如希望使用Java NIO,也可以创建Java NIO中的SocketChannel对象. 创建Socket 下面的示例代码是连接到IP地址为78.64.84.171服务器上的80端口,这台服务器就是我们的Web服务器(www.jb51.net),而80端口就是Web服务端口. 复制代码 代码如下: Socket socket = new Socket("78.46.84.

  • java使用TimerTask定时器获取指定网络数据

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.URL;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask; public class GetYinInf

  • java网络编程学习java聊天程序代码分享

    复制代码 代码如下: package com.neusoft.edu.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;/** * 服务器端代码 * 获取客户端发送的信息,显示并且返回对应的回复 *

  • Java用文件流下载网络文件示例代码

    复制代码 代码如下: public HttpServletResponse download(String path, HttpServletResponse response) {        try {            // path是指欲下载的文件的路径.            File file = new File(path);            // 取得文件名.            String filename = file.getName();          

  • java如何测试网络连通性

    本文实例为大家分享了Java测试网络连通性的方法,供大家参考,具体内容如下 第一种方式:利用java运行时: Java代码 /** * test network * @param ip */ private void getNetworkState(String ip) { Runtime runtime = Runtime.getRuntime(); try { log.info("=================正在测试网络连通性ip:"+ip); Process process

  • java网络编程之socket网络编程示例(服务器端/客户端)

    Java为TCP协议提供了两个类,分别在客户端编程和服务器端编程中使用它们.在应用程序开始通信之前,需要先创建一个连接,由客户端程序发起:而服务器端的程序需要一直监听着主机的特定端口号,等待客户端的连接.在客户端中我们只需要使用Socket实例,而服务端要同时处理ServerSocket实例和Socket实例;二者并且都使用OutputStream和InpuStream来发送和接收数据. 学习一种知识最好的方式就是使用它,通过前面的笔记,我们已经知道如何获取主机的地址信息,现在我们通过一个简单的

随机推荐