- public class HttpTest {
-
- String urlString;
- static void main(String[] args) throws Exception {
- HttpTest client = new HttpTest("http://fuss10.elemecdn.com/d/92/bc7be757f0bf1931cee6d23e75ae7jpeg.jpeg");
- client.run();
- }
- public HttpTest(String urlString) {
- this.urlString = urlString;
- }
- public void run() throws Exception {
- //生成一个URL对象
- URL url = new URL(urlString);
- //打开URL
- HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
- urlConnection.setRequestProperty("User-Agent", "Mozilla/31.0 (compatible; MSIE 10.0; Windows NT; DigExt)");
- urlConnection.setConnectTimeout(5000);
- urlConnection.setReadTimeout(60000);
- //得到输入流,即获得了网页的内容
- BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:/aa.jpeg"));
- byte[] buff = new byte[1024];
- int len = 0;
- // 读取输入流的数据,并显示
- while ((len = bis.read(buff))>0){
- bos.write(buff, 0, len);
- }
- bis.close();
- bos.close();
- }
- }
复制代码 |
|