代码如下:(通过定时功能,获取每天货币汇率)
1、设置 网站内容的编码格式
/** 8 位 UCS 转换格式 */
public static final String UTF_8 = "UTF-8";
public String toUTF_8(String str) throws UnsupportedEncodingException{
return this.changeCharset(str, UTF_8);
}
/**
* 字符串编码转换的实现方法
* @param str 待转换编码的字符串
* @param newCharset 目标编码
* @return
* @throws UnsupportedEncodingException
*/
public String changeCharset(String str, String newCharset)
throws UnsupportedEncodingException {
if (str != null) {
//用默认字符编码解码字符串。
byte[] bs = str.getBytes();
//用新的字符编码生成字符串
return new String(bs, newCharset);
}
return null;
}
注:以text文本的形式 查看 网页源代码 ;点击“另存为”,在弹出窗中最下面可以看到网站使用的编码格式;
2、编码操作代码
public class AutoCode {
public static void main(String[] args) {
AutoCode ac = new AutoCode();
try {
// 设置代理, 如果无代理,则省略
Properties prop = System.getProperties();
prop.put("http.proxyHost","192.168.28.3");
prop.put("http.proxyPort","8080");
// 创建http 链接
String beforeUrl = http://www.pbc.gov.cn/publish/zhengcehuobisi/637/index.html;
URL url2 = new URL(beforeUrl);
HttpURLConnection conn2= (HttpURLConnection) url2.openConnection();
// 获取链接输入流(网站汇率信息包括在此流中)
InputStreamReader in2 = new InputStreamReader(conn2.getInputStream());
BufferedReader read2 = new BufferedReader(in2);
String s2;
//打印http url链接的内容
StringBuffer resultBuffer2 = new StringBuffer();
while((s2 = read2.readLine()) != null) {
resultBuffer2.append(s2);
resultBuffer2.append("\n");
}
in2.close();
s2 = resultBuffer2.toString();
s2 = ac.toUTF_8(s2); //调用编码格式方式
System.out.println(s2);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注:如果需要获取网页中某一些内容,可以通过String的方法进行操作;
比如:indexof() 查看某字段或字符串的位置;
substring() 截图某一个范围内的内容;
等等,其他的可以在网上搜索;
如果有更好获取指定网页内容的方式,欢迎讨论