search
HomeJavajavaTutorialJava multi-threading captures ringtone data from the official website of Ringtone Duoduo

一直想练习下java多线程抓取数据。

有天被我发现,铃声多多的官网(http://www.shoujiduoduo.com/main/)有大量的数据。

通过观察他们前端获取铃声数据的ajax

Java multi-threading captures ringtone data from the official website of Ringtone Duoduo

http://www.shoujiduoduo.com/ringweb/ringweb.php?type=getlist&listid={类别ID}&page={分页页码}

很容易就能发现通过改变 listId和page就能从服务器获取铃声的json数据, 通过解析json数据,

可以看到都带有{"hasmore":1,"curpage":1}这样子的指示,通过判断hasmore的值,决定是否进行下一页的抓取。

但是通过上面这个链接返回的json中不带有铃声的下载地址

很快就可以发现,点击页面的“下载”会看到

通过下面的请求,就可以获取铃声的下载地址了

http://www.shoujiduoduo.com/ringweb/ringweb.php?type=geturl&act=down&rid={铃声ID}

Java multi-threading captures ringtone data from the official website of Ringtone Duoduo

所以,他们的数据是很容易被偷的。于是我就开始...

源码已经发在github上。如果感兴趣的童鞋可以查看

github:https://github.com/yongbo000/DuoduoAudioRobot

上代码:

<pre class="brush:java;">package me.yongbo.DuoduoRingRobot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
/* * @author yongbo_ * @created 2013/4/16 * * */
public class DuoduoRingRobotClient implements Runnable {
public static String GET_RINGINFO_URL = "http://www.shoujiduoduo.com/ringweb/ringweb.php?type=getlist&listid=%1$d&page=%2$d";
public static String GET_DOWN_URL = "http://www.shoujiduoduo.com/ringweb/ringweb.php?type=geturl&act=down&rid=%1$d";
public static String ERROR_MSG = "listId为 %1$d 的Robot发生错误,已自动停止。当前page为 %2$d";public static String STATUS_MSG = "开始抓取数据,当前listId: %1$d,当前page: %2$d";
public static String FILE_DIR = "E:/RingData/";public static String FILE_NAME = "listId=%1$d.txt";private boolean errorFlag = false;private int listId;private int page;
private int endPage = -1;private int hasMore = 1;
private DbHelper dbHelper;
/** * 构造函数 * @param listId 菜单ID * @param page 开始页码 * @param endPage 结束页码 * */
public DuoduoRingRobotClient(int listId, int beginPage, int endPage)
 {this.listId = listId;this.page = beginPage;this.endPage = endPage;this.dbHelper = new DbHelper();}
/** * 构造函数 * @param listId 菜单ID * @param page 开始页码 * */
public DuoduoRingRobotClient(int listId, int page) {this(listId, page, -1);}
/** * 获取铃声 * */public void getRings() {String url = String.format(GET_RINGINFO_URL, listId, page);String responseStr = httpGet(url);hasMore = getHasmore(responseStr);
page = getNextPage(responseStr);
ringParse(responseStr.replaceAll("\\{\"hasmore\":[0-9]*,\"curpage\":[0-9]*\\},", "").replaceAll(",]", "]"));}/** * 发起http请求 * @param webUrl 请求连接地址 * */public String httpGet(String webUrl){URL url;URLConnection conn;StringBuilder sb = new StringBuilder();String resultStr = "";try {url = new URL(webUrl);conn = url.openConnection();conn.connect();InputStream is = conn.getInputStream();InputStreamReader isr = new InputStreamReader(is);BufferedReader bufReader = new BufferedReader(isr);String lineText;while ((lineText = bufReader.readLine()) != null) {sb.append(lineText);}resultStr = sb.toString();} catch (Exception e) {errorFlag = true;//将错误写入txtwriteToFile(String.format(ERROR_MSG, listId, page));}return resultStr;}/** * 将json字符串转化成Ring对象,并存入txt中 * @param json Json字符串 * */public void ringParse(String json) {Ring ring = null;JsonElement element = new JsonParser().parse(json);JsonArray array = element.getAsJsonArray();// 遍历数组Iterator<JsonElement> it = array.iterator();
Gson gson = new Gson();while (it.hasNext() && !errorFlag) {JsonElement e = it.next();// JsonElement转换为JavaBean对象ring = gson.fromJson(e, Ring.class);ring.setDownUrl(getRingDownUrl(ring.getId()));if(isAvailableRing(ring)) {System.out.println(ring.toString());
//可选择写入数据库还是写入文本//writeToFile(ring.toString());writeToDatabase(ring);}}}
/** * 写入txt * @param data 字符串 * */public void writeToFile(String data)
 {String path = FILE_DIR + String.format(FILE_NAME, listId);File dir = new File(FILE_DIR);File file = new File(path);FileWriter fw = null;if(!dir.exists()){dir.mkdirs();
}try {if(!file.exists()){file.createNewFile();}fw = new FileWriter(file, true);
fw.write(data);fw.write("\r\n");fw.flush();} catch (IOException e) {
// TODO Auto-generated catch blocke.printStackTrace();
}finally {try {if(fw != null){fw.close();}} catch (IOException e) {
// TODO Auto-generated catch blocke.printStackTrace();}}}/** * 写入数据库 * @param ring 一个Ring的实例 * */
public void writeToDatabase(Ring ring) {dbHelper.execute("addRing", ring);}
@Overridepublic void run() {while(hasMore == 1 && !errorFlag){if(endPage != -1){if(page > endPage) { break; }}System.out.println(String.format(STATUS_MSG, listId, page));
getRings();System.out.println(String.format("该页数据写入完成"));}System.out.println("ending...");}
private int getHasmore(String resultStr){Pattern p = Pattern.compile("\"hasmore\":([0-9]*),\"curpage\":([0-9]*)"); 
 Matcher match = p.matcher(resultStr);  
 if (match.find()) {  return Integer.parseInt(match.group(1));
  }  return 0;
}
private int getNextPage(String resultStr){Pattern p = Pattern.compile("\"hasmore\":([0-9]*),\"curpage\":([0-9]*)");Matcher match = p.matcher(resultStr);if (match.find()) {return Integer.parseInt(match.group(2));}return 0;}
/** * 判断当前Ring是否满足条件。当Ring的name大于50个字符或是duration为小数则不符合条件,将被剔除。 * @param ring 当前Ring对象实例 * */private boolean isAvailableRing(Ring ring){Pattern p = Pattern.compile("^[1-9][0-9]*$");
Matcher match = p.matcher(ring.getDuration());
if(!match.find()){return false;}if(ring.getName().length() > 50 || ring.getArtist().length() > 50 || ring.getDownUrl().length() == 0){return false;}return true;}
/** * 获取铃声的下载地址 * @param rid 铃声的id * */
public String getRingDownUrl(String rid){String url = String.format(GET_DOWN_URL, rid);
String responseStr = httpGet(url);return responseStr;}}

更多Java multi-threading captures ringtone data from the official website of Ringtone Duoduo相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详解Java中volatile关键字的使用场景及其作用详解Java中volatile关键字的使用场景及其作用Jan 30, 2024 am 10:01 AM

Java中volatile关键字的作用及应用场景详解一、volatile关键字的作用在Java中,volatile关键字用于标识一个变量在多个线程之间可见,即保证可见性。具体来说,当一个变量被声明为volatile时,任何对该变量的修改都会立即被其他线程所知晓。二、volatile关键字的应用场景状态标志volatile关键字适用于一些状态标志的场景,例如一

文件读取多线程加速性能的Java开发优化方法文件读取多线程加速性能的Java开发优化方法Jun 30, 2023 pm 10:54 PM

Java开发中,文件读取是一个非常常见且重要的操作。随着业务的增长,文件的大小和数量也不断增加。为了提高文件读取的速度,我们可以采用多线程的方式来并行读取文件。本文将介绍如何在Java开发中优化文件读取多线程加速性能。首先,在进行文件读取前,我们需要先确定文件的大小和数量。根据文件的大小和数量,我们可以合理地设定线程的数量。过多的线程数量可能会导致资源浪费,

Java多线程环境下的异常处理Java多线程环境下的异常处理May 01, 2024 pm 06:45 PM

多线程环境下异常处理的要点:捕捉异常:每个线程使用try-catch块捕捉异常。处理异常:在catch块中打印错误信息或执行错误处理逻辑。终止线程:无法恢复时,调用Thread.stop()终止线程。UncaughtExceptionHandler:处理未捕获异常,需要实现该接口并指定给线程。实战案例:线程池中的异常处理,使用UncaughtExceptionHandler来处理未捕获异常。

探索java多线程的工作原理和特点探索java多线程的工作原理和特点Feb 21, 2024 pm 03:39 PM

探索Java多线程的工作原理和特点引言:在现代计算机系统中,多线程已成为一种常见的并发处理方式。Java作为一门强大的编程语言,提供了丰富的多线程机制,使得程序员可以更好地利用计算机的多核处理器、提高程序运行效率。本文将探索Java多线程的工作原理和特点,并通过具体的代码示例来说明。一、多线程的基本概念多线程是指在一个程序中同时执行多个线程,每个线程处理不同

Java多线程调试技术揭秘Java多线程调试技术揭秘Apr 12, 2024 am 08:15 AM

多线程调试技术解答:1.多线程代码调试的挑战:线程之间的交互导致复杂且难以跟踪的行为。2.Java多线程调试技术:逐行调试线程转储(jstack)监视器进入和退出事件线程本地变量3.实战案例:使用线程转储发现死锁,使用监视器事件确定死锁原因。4.结论:Java提供的多线程调试技术可以有效解决与线程安全、死锁和争用相关的问题。

Java多线程性能优化指南Java多线程性能优化指南Apr 11, 2024 am 11:36 AM

Java多线程性能优化指南提供了五个关键优化点:减少线程创建和销毁开销避免不当的锁争用使用非阻塞数据结构利用Happens-Before关系考虑无锁并行算法

Java中的多线程安全问题——java.lang.ThreadDeath的解决方法Java中的多线程安全问题——java.lang.ThreadDeath的解决方法Jun 25, 2023 am 11:22 AM

Java是一种广泛应用于现代软件开发的编程语言,其多线程编程能力也是其最大的优点之一。然而,由于多线程带来的并发访问问题,Java中常常会出现多线程安全问题。其中,java.lang.ThreadDeath就是一种典型的多线程安全问题。本文将介绍java.lang.ThreadDeath的原因以及解决方法。一、java.lang.ThreadDeath的原因

Java多线程并发锁详解Java多线程并发锁详解Apr 11, 2024 pm 04:21 PM

Java并发锁机制可确保多线程环境下,共享资源仅由一个线程访问。其类型包括悲观锁(获取锁再访问)和乐观锁(访问后检查冲突)。Java提供了ReentrantLock(互斥锁)、Semaphore(信号量)和ReadWriteLock(读写锁)等内置并发锁类。使用这些锁可以确保共享资源的线程安全访问,如确保多个线程同时访问共享变量counter时仅有一个线程更新其值。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)