100分求解一个问题
我想写一个方法
方法的传入参数是URL,方法的返回结果是该URL的源文件。
如传入www.163.com,要求返回的是点浏览器的查看--查看源文件后得到的那个文本文件。jdk的API里面不知道有没有什么现成的方法好用?望高手指点,谢谢。
------解决方案--------------------当然可以,而且很简单用java.net就可以了,把主要提示给你列到如下,你应该很容易就看懂了
import java.io.BufferedReader;
import
java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
//sb.append(line + "\n ");
sb.append(line);
}
Thanks
Hima
------解决方案--------------------import java.io.*;
import java.net.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class ReadHtml {
public static String readHtmlFile(String urlPath){
String htmlFile= " ";
try {
URL url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
urlConnection.setAllowUserInteraction(false);
// InputStream urlStream = url.openStream();
InputStream urlStream = urlConnection.getInputStream();//.openStream();
InputStreamReader sr = new InputStreamReader(urlStream, "GBK ");
int byteRead = 0;
char[] buffer = new char[8192];
while ((byteRead = sr.read(buffer, 0, 8192)) != -1) {
System.out.println(new String(buffer,0, byteRead));
htmlFile+=new String(buffer,0, byteRead);
}
} catch (
IOException e) {
System.out.println( "error : " + e.getMessage());
}
return htmlFile;
}
public static void main(String[] args){
String urlGk= "http://gaokao.h-edu.com/yx/yxjj.asp?schoolid=85 ";
String htmlContent=readHtmlFile(urlGk);
String r= " <span class=\ "fb14\ "> ([^\ "]+) </span> ";
Pattern s=Pattern.compile(r);
Matcher m=s.matcher(htmlContent);
System.out.println( "名称为 "+m.group(1));
}
}
------解决方案--------------------简单点这样就可以了:
URL url = new URL( "http://www.163.com/ ");
InputStream in = url.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str = null;
while ((str = br.readLine()) != null)
System.out.println(str);
in.close();
br.close();
------解决方案--------------------学好基础知识:
http://www.elearning.gov.cn/elearning/user/findclass.do?method=courselist&categoryid=57982540b6cd11d993d0f770c0a83c70&id=2