不需要添加任何jar文件就可以通过网站连接来得到网站的html源代码
URL url = new URL("http://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream(); // 通过输入流获得网站数据
byte[] getData = readInputStream(inputStream); // 获得网站的二进制数据
其中readInputStream(InputStream)方法非常重要,可以把InputStream对象中的流读出来,存储为Byte数组的形式,代码如下:
//把InputStream里面的数据转化为byte数组,返回。该方法很重要!
public static byte[] readInputStream(InputStream inputStream)
throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len) ;
}
bos.close();
return bos.toByteArray();
}
最后一步把byte数组处理一下,编程字符串形式,就可以随便处理了。将byte[] ----> String 方法如下:
public String parseByteArrayToString(byte[] buf){
return new String(buf) ; //构造方法也可以是String(byte[], Encoding), 这样可以对新构造的字符串进行编码方面的控制
}
程序源码以及测试如下:(把原文件读出来转为字符串存储在txt文件)
package FromBottom;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class HtmlRequest {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.baidu.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream(); // 通过输入流获得网站数据
byte[] getData = readInputStream(inputStream); // 获得网站的二进制数据
newToFile(getData) ;
//toFile_good("log_tofilegood.txt", data, "UTF-8") ;
//toFile2(data) ;
}
//把InputStream里面的数据转化为byte数组,返回。该方法很重要!
public static byte[] readInputStream(InputStream inputStream)
throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len) ;
}
bos.close();
return bos.toByteArray();
}
// 将String写入文件,这个方法可以运行没问题。
public static void toFile_good(String filename, String string,
String charset) throws IOException {
Charset cs = Charset.forName(charset);
CharsetEncoder coder = cs.newEncoder();
FileOutputStream stream = new FileOutputStream(filename, true);
OutputStreamWriter writer = new OutputStreamWriter(stream, coder);
writer.write(string, 0, string.length());
writer.close();
}
//使用FileWriter将String写入文件,运行没问题
public static void toFile2(String content) throws Exception{
FileWriter fw = new FileWriter(new File("log.txt")) ;
fw.write(content) ;
fw.close() ;
}
//这个方法可以把字符串完整的输出到txt文件,参数为byte数组,运行没问题
public static void newToFile(byte[] buf) throws IOException{
FileWriter fw = new FileWriter("newToFile.txt") ;
BufferedWriter bw = new BufferedWriter(fw) ;
String str = new String(buf, "UTF-8") ;
System.out.println(str) ;
bw.write(str) ;
bw.flush() ;
bw.close() ;
fw.close() ;
}
}