import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * 通过URL,从网络下载图片 * @author TF */ public class ImageRequest { public static void main(String[] args) throws Exception { //图片的地址 URL url = new URL( "http://a.vpimg1.com/upload/brand/201407/2014071414241844761.jpg"); //得到http链接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置请求方法 conn.setRequestMethod("GET"); //设置请求超时时间 conn.setConnectTimeout(5 * 1000); // 通过输入流获取图片数据 InputStream is = conn.getInputStream(); // 得到图片的二进制数据 byte[] data = readInputStream(is); File imageFile = new File("creep.jpg"); FileOutputStream outStream = new FileOutputStream(imageFile); outStream.write(data); outStream.close(); } 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(); } }
这样,图片就下载下来了,保存在当前的工程下面。刷新一下工程,就能看见。
(2)在java中,通过网络,解析一个网站,得到它的html代码。
/** * 通过URL解析网址,得到html文件 * @author TF */ public class HtmlRequest { public static void main(String[] args) throws Exception { URL url = new URL("http://www.baidu.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 *1000); //通过输入流获取html数据 InputStream is = conn.getInputStream(); //得到html的二进制数据 byte[] data = readInputStream(is); String html = new String(data, "UTF-8"); System.out.println(html); } public static byte[] readInputStream(InputStream instream) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1 * 1024]; int length = 0; while(-1 != (length = instream.read(buffer))){ baos.write(buffer, 0, length); } instream.close(); return baos.toByteArray(); } }这样,在控制台就能看到解析完成的百度首页的html代码了...
java学习篇(一)从网络下载图片,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u012301841/article/details/37813861