利用代码实现获取网站的内容(自动获取每天货币汇率)

代码如下:(通过定时功能,获取每天货币汇率)

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() 截图某一个范围内的内容;

等等,其他的可以在网上搜索;

 

如果有更好获取指定网页内容的方式,欢迎讨论

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值