频道栏目
首页 > 资讯 > 其他 > 正文

使用url读取csdn的博客访问量并将记录保存到本地

16-10-22        来源:[db:作者]  
收藏   我要投稿

今天晚上我发现我有一个毛病 总喜欢看自己的博客访问量。。。

看着一点一点的增加 就有一种学习,写博客的动力

记得以前自己记录下来时间 然后记录下访问量 ...想想好幼稚

既然想成为一个程序员 当然要方便自己了~

所以就写了一个小程序

开始了

既然要读取你的博客访问量 找到你csdn的随便一篇文章 或者主页。(比如我的:http://blog.csdn.net/su20145104009?viewmode=contents)

URL url = new URL("http://blog.csdn.net/su20145104009?viewmode=contents");

而为了csdn服务器端禁止抓取,那么这个你可以通过设置User-Agent来欺骗服务器.

connection = url.openConnection();
//User-Agent来欺骗服务器. 避免出现错误代码403
connection.setRequestProperty("User-Agent",Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
开始通信了~
connection.connect();
下面 ,需要读取网页的内容 ,肯定要用到"工具"
InputStream is = null;
//字符流
InputStreamReader isr = null;
//缓冲流
BufferedReader br = null;
//网页编码
String context = null;

读取内容

//获得网页的字节输入流
is = connection.getInputStream();
//将字节输入流转换为字符输入流 并设置转码格式为utf-8
isr = new InputStreamReader(is, "utf-8");
//将字符流转换为缓冲流
br = new BufferedReader(isr);
然后就是读取存在缓冲流的内容,保存在context
//一行一行读取网页内容
context = br.readLine();
while (br.readLine() != null) {
context += br.readLine();
}

context里面是网页的源码 ,内容那么多 怎么得到我们想要的信息呢? 是的,正则表达式 不懂得给你分享个视频

正则表达式视频

//通过正则表达式 获得访问人气那一行html代码
	private static void deal(String context) {
		String regex = "
  • 访问:.{1,10}次
  • "; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(context); if (m.find()) { //m.group(0)为匹配到的内容 通过getCount方法处理得到访问数量 int count = getCount(m.group(0)); //写入到文本内容 write(count); } }

     

    得到当前访问量count 剩下就是写入到文本。不过我还特意加了一个功能 首先读取上一次的访问量 求差 增加了多少~


    由于我文件的是保存到桌面 所以首先获得桌面路径

     

    	File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
    	String desktopPath = desktopDir.getAbsolutePath();

    然后设置文件的路径

     

     

    File file = new File(desktopPath + "/blogView.txt");

    如果文件不存在 就新建

     

     

    if (!file.exists()) {
    	file.createNewFile();
    }

    如果存在 就是用bufferedReader读取信息

     

     

    br = new BufferedReader(new FileReader(file));

    由于一次只能读取一行 ,而我们要获得的是文件中最后一次的访问量

     

    所以需要一个中间变量

    具体如下:

     

    String preBlogView = null;
    //中间变量
    String temp = null;
    while ((temp = br.readLine()) != null) {
    	preBlogView = temp;
    }
    然后使用getCount处理得到的信息,返回上次的访问量
    //得到上次访问人气
    int preCount = getCount(preBlogView);

    然后就是写入了~

    不再说

     

    			// 获得当前日期
    			Date date = new Date();
    			SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm:ss a");
    			writeContext += "当前访问量:" + count + "人\t";
    			writeContext += sdf.format(date) + "\t";
    			writeContext += "增加了" + (count - preCount) + "人";
    			bw.write(writeContext);
    			//换行
    			bw.newLine();



     

     

相关TAG标签
上一篇:Android开发学习之路--Android Studio cmake编译ffmpeg
下一篇:Android开发:为什么要使用Kotlin?
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站