package cn.itcast.service;//其实就是从网络获取byte 然后转换成文件 import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import cn.itcast.utils.StreamTool; public class HtmlService { public static String getHtml(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();// 通过输入流获取html数据 byte[] data = StreamTool.readInputStream(inStream);// 得到html的二进制数据 DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("sdcard/tips.txt"));//把byte写入文件 dataOutputStream.write(data); dataOutputStream.flush(); String html = new String(data, "utf-8"); return html; } }
package cn.itcast.utils;import java.io.ByteArrayOutputStream;import java.io.InputStream;public class StreamTool { /** * 从输入流中获取数据 * @param inStream 输入流 * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); }}