java URL类、URLConnection类读取html或xml信息

来源:互联网 发布:德儿塔青少儿编程 编辑:程序博客网 时间:2024/05/29 17:31
package com.risencn.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.risencn.service.WcmPhoneService;
import com.risencn.serviceimpl.WcmPhoneServiceimpl;

public class WcmPhoneTest {
      public static void main(String[] args) {
          
          ios_index();
      }
      public static String ios_index(){
          //调用业务方法
           WcmPhoneService service=new WcmPhoneServiceimpl();
           //url地址
         String urlstr= service.ios_index();
         System.out.println("urlstr:"+urlstr);
         //StringBuffer存放
         StringBuffer strs=new StringBuffer();
         try {
            URL url=new URL(urlstr);
            // 此处的urlConnection对象实际上是根据URL的
            URLConnection conn=url.openConnection();
             //  取得输入流,并使用Reader读取
            BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line = null;
            while((line=reader.readLine()) !=null)
                strs.append(line + " ");
                reader.close();            
        } catch (Exception e) {
            e.printStackTrace();
        }
        String htmlxmlStr=strs.toString();
        System.out.println("htmlStr:"+htmlxmlStr);
        return htmlxmlStr;             
    }
          
}