获取网页源代码并解决字符乱码的问题

给大家推荐个靠谱的公众号程序员探索之路,大家一起加油https://i-blog.csdnimg.cn/blog_migrate/93320939ba8f8b0a898e29429753f496.png

每当闲的时候就会刷新一下访问次数,还得刷新页面,作为一个程序员当然不会这么low

写一个程序获得访问次数

package com.lean.zzh;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class VisitorVolume {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		URL url = new URL("http://blog.csdn.net/yueloveme");
		System.out.println(getNum(get(url)));
	}

	/**
	 * 获取网页上的源码
	 * 
	 * @throws IOException
	 */
	public static String get(URL url) throws IOException {
		String times = null;
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5 * 1000);
		InputStream read = conn.getInputStream();
		byte[] infor = new byte[1024];
		int len = 0;
		while ((len = read.read(infor)) != -1) {
			// 网页的编码格式是utf-8的,所以每一次转换都得指定格式才不会乱码
			times += new String(infor, 0, len, "utf-8");
		}
		read.close();
		return times;
	}
	/**
	 * 获取访问量
	 */
	public static String getNum(String information) {
		String num = null;
		int start = information.indexOf("blog_rank");
		start = information.indexOf("<span>", start + 1);
		int end = information.indexOf("</span>", start);
		num = information.substring(start + 6, end);
		return num;
	}
}

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值