爪哇国新游记之二十九----访问URL获取输入流

代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class HttpReader{
    private String urlStr;

    private String result;
    
    public HttpReader(String urlStr) throws Exception{
        if(urlStr.startsWith("http://")){
            this.urlStr=urlStr;
        }else{
            this.urlStr="http://"+urlStr;
        }
        
        URL url = new URL(urlStr);// 创建URL对象
        InputStream is = url.openStream();// 获取url中的输入流
        BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));// 指定编码格式,否则容易乱码
        
        StringBuilder sb=new StringBuilder();
        while(reader.ready()){
            sb.append(reader.readLine());
        }
        
        result=sb.toString();
        
        saveResult();
    }
    
    private void saveResult(){
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("c://result.html"));
            out.write(result);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public String getUrlStr() {
        return urlStr;
    }

    public String getResult() {
        return result;
    }
    
    public static void main(String[] args) throws Exception{
        HttpReader r=new HttpReader("http://www.youdao.com/");
        System.out.println(r.getResult());
    }
}

输出:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no" /><meta name="keywords" content="有道, 搜索, 词典, 翻译, 云笔记, 笔记, 惠惠网, 惠惠购物助手, 购物搜索, 图片搜索, 视频搜索, 新闻搜索, 网易有道, 在线翻译, 专业翻译"><meta name="description" content="网易旗下搜索引擎,主要提供网页、图片、热闻、视频、音乐、博客等传统搜索服务,同时推出海量词典、阅读、购物搜索等创新型产品。" /><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE100"><title>有道首页</title><link rel='shortcut icon' href='http://shared.ydstatic.com/images/favicon.ico' type='image/x-icon'/><link href='http://shared.ydstatic.com/plugins/search-provider.xml' title='有道网页搜索' type='application/opensearchdescription+xml' rel='search'/><link rel="stylesheet" type="text/css" href="http://shared.ydstatic.com/images/myth/css/index_min.css?201311221"><style type="text/css">#logo{    background-image: url('http://shared.ydstatic.com/images/myth/images/logo.png');    _background:none;    _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://shared.ydstatic.com/images/skins/default/logo.png",sizingMethod="crop");}.s-btn-w{    background-color: #F63141;    background-image: url(http://shared.ydstatic.com/images/myth/images/btn-search.jpg);}.s-btn-w:hover{background-color: #E70A1B;}</style><link rel="canonical" href="http://www.youdao.com" /><script>var senders=[],senderIndex=0;function sendRequest(a){var c=Math.random(),b=new Image;b.src=a+"&_="+c;senderIndex>=50&&(senderIndex=0);senders[senderIndex++]=b}function requestLog(a,c){sendRequest("/requestlog?type="+a+"&"+c)} function recordSearchTime(){var a=(new Date).getTime();document.cookie="sbt="+a+";path=/;domain="+document.domain;return!0}var scope = {currentTimes : "1407294262857"};</script></head><body><div id="w">    <div id="n"><div class="w">                <ul>            <li class="cd"><a onmousedown="requestLog('FUNC_HIT','click=daohang.dict');" hidefocus="true" data-p="dict" href="http://dict.youdao.com/"><i></i>有道词典</a></li>            <li class="sp">|</li>            <li class="bj"><a onmousedown="requestLog('FUNC_HIT','click=daohang.note');" hidefocus="true" data-p="note" href="http://note.youdao.com"><i></i>有道云笔记</a></li>            <li class="sp">|</li>            <li class="hh"><a onmousedown="requestLog('FUNC_HIT','click=daohang.huihui');" hidefocus="true" data-p="huihui" href="http://www.huihui.cn"><i></i>惠惠</a></li>            <li class="sp">|</li>            <li class="fy"><a onmousedown="requestLog('FUNC_HIT','click=daohang.fanyi');" hidefocus="true" data-p="fanyi" href="http://fanyi.youdao.com/"><i></i>有道翻译</a></li>        </ul>    </div></div>    <div class="sp1"></div>    <div id="x" class="w">        <div id="logo"></div><div id="fm">            <form onsubmit="return recordSearchTime();" method="get"                action="http://www.youdao.com/search" class="c-fm-w">                <span class="s-inpt-w">                    <input type="text" class="s-inpt" autocomplete="off" name="q" id="query"/>                </span><span class="s-btn-w">                    <input type="submit" class="s-btn" id="qb" value="搜 索"/>                </span>                <input type="hidden" name="ue" value="utf8"/>                <input type="hidden" name="keyfrom" value="web.index"/>                                                <div id="jslct">                    <label>网页<i></i></label>                    <span style="display:none;">                        <a href="javascript:void(0)" rel="nofollow"                            tabname="web" action="http://www.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.www');">网页</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="image" action="http://image.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.image');">图片</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="video" action="http://video.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.video');">视频</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="dict" action="http://dict.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.dict');">词典</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="hotnews" action="http://news.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.news');">热闻</a>                    </span>                </div>                <div class="sg-wrap" style="display:none;">                    <table width="100%" cellspacing="0" cellpadding="0" border="0"><tr>                        <td valign="top"><ul class="sg-result-list"></ul></td>                        <td class="sob-wrap"></td>                    </tr></table>                </div>            </form>        </div>    </div>        <div class="sp2"></div>    <div id="sb" class="w">                                                                <a target="_blank" class="dict" href="http://i.clkservice.youdao.com/clk/request.s?d=http%3A%2F%2Fcidian.youdao.com&k=o%2FT7F5bBiEHMlbRm7gTkxXSGW9P0Qrv2v4qYNS19NxvXxo%2BoRxcJpjjAgKuViCqvfJnuc%2B0yzJOsONkc3PJ1iVqD8VAIUlsn4qNPWZUHpkJ1BZaSfmYAQyhU%2BQjqBVMZpkzSjMe5XvTUl4LtbQW4%2B8445qDU4eSWm%2FJiuZItbKDNGWtT0jlu98xZHT52jH3ceqQsyW275Pl3UZDPgfxQs9fGj6hHFwmmOMCAq5WIKq%2FXxo%2BoRxcJpjjAgKuViCqvkxAUca3IobmPAzAeuQ9o92eIt%2F36fCZAu22VryJeFyQ%3D&s=-1" hidefocus="true">            <img src="http://oimageb4.ydstatic.com/image?id=-4617966838173629374&product=adpublish" alt="词典图片" /><i></i>        </a><a target="_blank" class="note" href="http://i.clkservice.youdao.com/clk/request.s?d=http%3A%2F%2Fnote.youdao.com&k=o%2FT7F5bBiEHMlbRm7gTkxfknb%2B2ZSqn%2FqLoETHwC0TrXxo%2BoRxcJpjjAgKuViCqvfJnuc%2B0yzJOsONkc3PJ1iQFLXfdNs%2FeQxQJlzxPs63R1BZaSfmYAQyhU%2BQjqBVMZqpro20qkHCkkGGm0KWccTM445qDU4eSWm%2FJiuZItbKDcwQY%2F9cWlp1J%2BoABn2NHKMXreAiiJjOGvOzOXd7CnFNfGj6hHFwmmOMCAq5WIKq%2FXxo%2BoRxcJpjjAgKuViCqvPd0ndhCDLi%2BryLv7aTV9rmYS%2B2k8%2B%2Fz1%2Flj8c135Sjo%3D&s=-1" hidefocus="true">            <img src="http://oimagec5.ydstatic.com/image?id=308576524332959290&product=adpublish" alt="笔记" /><i></i>        </a><a target="_blank" class="huihui" href="http://i.clkservice.youdao.com/clk/request.s?d=http%3A%2F%2Fwww.huihui.cn%2F%3Fkeyfrom%3Dydsearch0620&k=o%2FT7F5bBiEHMlbRm7gTkxY9rCXWeAqpkTsfED%2BVSGfjXxo%2BoRxcJpjjAgKuViCqvfJnuc%2B0yzJOsONkc3PJ1iVVZGYmh5jpRIkGVHK0bQ3N1BZaSfmYAQyhU%2BQjqBVMZiUvOoH7AWFe2AnvhPeryLs445qDU4eSWm%2FJiuZItbKBR%2BFG7Taprgj7pVcBjpY7xWibWkVxpuHaYeBYln6vaLQvlZ1VT42n9MfP25O2IOenXxo%2BoRxcJpjjAgKuViCqv18aPqEcXCaY4wICrlYgqr9fGj6hHFwmmOMCAq5WIKq9HfSfzUz2S5TwWgrp3QzHi&s=-1" hidefocus="true">            <img src="http://oimagec8.ydstatic.com/image?id=4275989510430782538&product=adpublish" alt="惠惠" /><i></i>        </a>    </div>    <div class="sp3"></div>    <div id="f" class="w">        <a href="http://www.163.com/" onmousedown="requestLog('FUNC_HIT','click=footer.163');">            <img src="http://shared.ydstatic.com/images/myth/images/small-logo.jpg" alt="网易 NetEase" />        </a>        <div>            <a href="http://www.youdao.com/about" onmousedown="requestLog('FUNC_HIT','click=footer.about');">关于有道</a>            <span>|</span>            <a href="http://dsp.youdao.com/" onmousedown="requestLog('FUNC_HIT','click=footer.dsp');">有道智选</a>            <span>|</span>            <a href="http://i.youdao.com" onmousedown="requestLog('FUNC_HIT','click=footer.blog');">官方博客</a>            <span>|</span>            <a href="http://techblog.youdao.com/" onmousedown="requestLog('FUNC_HIT','click=footer.techblog');">技术博客</a>            <span>|</span>            <a href="http://campus.youdao.com/index.php?t1=index" onmousedown="requestLog('FUNC_HIT','click=footer.campus');">诚聘英才</a>            <span>|</span>            <a href="/contactus/contactus-page.html" onmousedown="requestLog('FUNC_HIT','click=footer.contactus');">?�滴颐?/a>        </div>        <div>?2014 <a href="http://www.163.com/" onmousedown="requestLog('FUNC_HIT','click=footer.163');">网易公司</a> <a href="http://www.youdao.com/terms/privacy.html" onmousedown="requestLog('FUNC_HIT','click=footer.privacy');">隐私政策</a> <a href="http://www.youdao.com/terms/index.html" onmousedown="requestLog('FUNC_HIT','click=footer.termindex');">服务条款</a> 京ICP证080268号 京公网安备110108003898号 </div>    </div></div><div id="snv" class="clear"><i><i></i></i></div><script type="text/javascript" src="http://shared.ydstatic.com/images/myth/js/index_min.js?201311221"></script><script type="text/javascript">(function (YD) {        var transData = function (data) {        var r = [], s = data.s, i = 0, l = s.length;        for (; i < l; i++) {            r.push({'c': s[i]});        }        return r;    };    var sug = YD.ui.suggest({        // source:"http://www.youdao.com/tglsuggest2/tglsuggest.s?keyfrom=web.index.suggest&o=" + .ns + "&rn=10&h=17&query="        source:"http://sug.so.360.cn/suggest/word?callback=YD.updateCall&encodein=utf-8&encodeout=utf-8&word="        ,menu: YD.cn("sg-wrap")[0], transData: transData    }, "query");})(getNS());</script></body></html>

文件内容:

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no" /><meta name="keywords" content="有道, 搜索, 词典, 翻译, 云笔记, 笔记, 惠惠网, 惠惠购物助手, 购物搜索, 图片搜索, 视频搜索, 新闻搜索, 网易有道, 在线翻译, 专业翻译"><meta name="description" content="网易旗下搜索引擎,主要提供网页、图片、热闻、视频、音乐、博客等传统搜索服务,同时推出海量词典、阅读、购物搜索等创新型产品。" /><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE100"><title>有道首页</title><link rel='shortcut icon' href='http://shared.ydstatic.com/images/favicon.ico' type='image/x-icon'/><link href='http://shared.ydstatic.com/plugins/search-provider.xml' title='有道网页搜索' type='application/opensearchdescription+xml' rel='search'/><link rel="stylesheet" type="text/css" href="http://shared.ydstatic.com/images/myth/css/index_min.css?201311221"><style type="text/css">#logo{    background-image: url('http://shared.ydstatic.com/images/myth/images/logo.png');    _background:none;    _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://shared.ydstatic.com/images/skins/default/logo.png",sizingMethod="crop");}.s-btn-w{    background-color: #F63141;    background-image: url(http://shared.ydstatic.com/images/myth/images/btn-search.jpg);}.s-btn-w:hover{background-color: #E70A1B;}</style><link rel="canonical" href="http://www.youdao.com" /><script>var senders=[],senderIndex=0;function sendRequest(a){var c=Math.random(),b=new Image;b.src=a+"&_="+c;senderIndex>=50&&(senderIndex=0);senders[senderIndex++]=b}function requestLog(a,c){sendRequest("/requestlog?type="+a+"&"+c)} function recordSearchTime(){var a=(new Date).getTime();document.cookie="sbt="+a+";path=/;domain="+document.domain;return!0}var scope = {currentTimes : "1407294262857"};</script></head><body><div id="w">    <div id="n"><div class="w">                <ul>            <li class="cd"><a onmousedown="requestLog('FUNC_HIT','click=daohang.dict');" hidefocus="true" data-p="dict" href="http://dict.youdao.com/"><i></i>有道词典</a></li>            <li class="sp">|</li>            <li class="bj"><a onmousedown="requestLog('FUNC_HIT','click=daohang.note');" hidefocus="true" data-p="note" href="http://note.youdao.com"><i></i>有道云笔记</a></li>            <li class="sp">|</li>            <li class="hh"><a onmousedown="requestLog('FUNC_HIT','click=daohang.huihui');" hidefocus="true" data-p="huihui" href="http://www.huihui.cn"><i></i>惠惠</a></li>            <li class="sp">|</li>            <li class="fy"><a onmousedown="requestLog('FUNC_HIT','click=daohang.fanyi');" hidefocus="true" data-p="fanyi" href="http://fanyi.youdao.com/"><i></i>有道翻译</a></li>        </ul>    </div></div>    <div class="sp1"></div>    <div id="x" class="w">        <div id="logo"></div><div id="fm">            <form onsubmit="return recordSearchTime();" method="get"                action="http://www.youdao.com/search" class="c-fm-w">                <span class="s-inpt-w">                    <input type="text" class="s-inpt" autocomplete="off" name="q" id="query"/>                </span><span class="s-btn-w">                    <input type="submit" class="s-btn" id="qb" value="搜 索"/>                </span>                <input type="hidden" name="ue" value="utf8"/>                <input type="hidden" name="keyfrom" value="web.index"/>                                                <div id="jslct">                    <label>网页<i></i></label>                    <span style="display:none;">                        <a href="javascript:void(0)" rel="nofollow"                            tabname="web" action="http://www.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.www');">网页</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="image" action="http://image.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.image');">图片</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="video" action="http://video.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.video');">视频</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="dict" action="http://dict.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.dict');">词典</a>                        <a href="javascript:void(0)" rel="nofollow"                            tabname="hotnews" action="http://news.youdao.com/search" onmousedown="requestLog('FUNC_HIT','click=nav.news');">热闻</a>                    </span>                </div>                <div class="sg-wrap" style="display:none;">                    <table width="100%" cellspacing="0" cellpadding="0" border="0"><tr>                        <td valign="top"><ul class="sg-result-list"></ul></td>                        <td class="sob-wrap"></td>                    </tr></table>                </div>            </form>        </div>    </div>        <div class="sp2"></div>    <div id="sb" class="w">                                                                <a target="_blank" class="dict" href="http://i.clkservice.youdao.com/clk/request.s?d=http%3A%2F%2Fcidian.youdao.com&k=o%2FT7F5bBiEHMlbRm7gTkxXSGW9P0Qrv2v4qYNS19NxvXxo%2BoRxcJpjjAgKuViCqvfJnuc%2B0yzJOsONkc3PJ1iVqD8VAIUlsn4qNPWZUHpkJ1BZaSfmYAQyhU%2BQjqBVMZpkzSjMe5XvTUl4LtbQW4%2B8445qDU4eSWm%2FJiuZItbKDNGWtT0jlu98xZHT52jH3ceqQsyW275Pl3UZDPgfxQs9fGj6hHFwmmOMCAq5WIKq%2FXxo%2BoRxcJpjjAgKuViCqvkxAUca3IobmPAzAeuQ9o92eIt%2F36fCZAu22VryJeFyQ%3D&s=-1" hidefocus="true">            <img src="http://oimageb4.ydstatic.com/image?id=-4617966838173629374&product=adpublish" alt="词典图片" /><i></i>        </a><a target="_blank" class="note" href="http://i.clkservice.youdao.com/clk/request.s?d=http%3A%2F%2Fnote.youdao.com&k=o%2FT7F5bBiEHMlbRm7gTkxfknb%2B2ZSqn%2FqLoETHwC0TrXxo%2BoRxcJpjjAgKuViCqvfJnuc%2B0yzJOsONkc3PJ1iQFLXfdNs%2FeQxQJlzxPs63R1BZaSfmYAQyhU%2BQjqBVMZqpro20qkHCkkGGm0KWccTM445qDU4eSWm%2FJiuZItbKDcwQY%2F9cWlp1J%2BoABn2NHKMXreAiiJjOGvOzOXd7CnFNfGj6hHFwmmOMCAq5WIKq%2FXxo%2BoRxcJpjjAgKuViCqvPd0ndhCDLi%2BryLv7aTV9rmYS%2B2k8%2B%2Fz1%2Flj8c135Sjo%3D&s=-1" hidefocus="true">            <img src="http://oimagec5.ydstatic.com/image?id=308576524332959290&product=adpublish" alt="笔记" /><i></i>        </a><a target="_blank" class="huihui" href="http://i.clkservice.youdao.com/clk/request.s?d=http%3A%2F%2Fwww.huihui.cn%2F%3Fkeyfrom%3Dydsearch0620&k=o%2FT7F5bBiEHMlbRm7gTkxY9rCXWeAqpkTsfED%2BVSGfjXxo%2BoRxcJpjjAgKuViCqvfJnuc%2B0yzJOsONkc3PJ1iVVZGYmh5jpRIkGVHK0bQ3N1BZaSfmYAQyhU%2BQjqBVMZiUvOoH7AWFe2AnvhPeryLs445qDU4eSWm%2FJiuZItbKBR%2BFG7Taprgj7pVcBjpY7xWibWkVxpuHaYeBYln6vaLQvlZ1VT42n9MfP25O2IOenXxo%2BoRxcJpjjAgKuViCqv18aPqEcXCaY4wICrlYgqr9fGj6hHFwmmOMCAq5WIKq9HfSfzUz2S5TwWgrp3QzHi&s=-1" hidefocus="true">            <img src="http://oimagec8.ydstatic.com/image?id=4275989510430782538&product=adpublish" alt="惠惠" /><i></i>        </a>    </div>    <div class="sp3"></div>    <div id="f" class="w">        <a href="http://www.163.com/" onmousedown="requestLog('FUNC_HIT','click=footer.163');">            <img src="http://shared.ydstatic.com/images/myth/images/small-logo.jpg" alt="网易 NetEase" />        </a>        <div>            <a href="http://www.youdao.com/about" onmousedown="requestLog('FUNC_HIT','click=footer.about');">关于有道</a>            <span>|</span>            <a href="http://dsp.youdao.com/" onmousedown="requestLog('FUNC_HIT','click=footer.dsp');">有道智选</a>            <span>|</span>            <a href="http://i.youdao.com" onmousedown="requestLog('FUNC_HIT','click=footer.blog');">官方博客</a>            <span>|</span>            <a href="http://techblog.youdao.com/" onmousedown="requestLog('FUNC_HIT','click=footer.techblog');">技术博客</a>            <span>|</span>            <a href="http://campus.youdao.com/index.php?t1=index" onmousedown="requestLog('FUNC_HIT','click=footer.campus');">诚聘英才</a>            <span>|</span>            <a href="/contactus/contactus-page.html" onmousedown="requestLog('FUNC_HIT','click=footer.contactus');">联系我们</a>        </div>        <div>?2014 <a href="http://www.163.com/" onmousedown="requestLog('FUNC_HIT','click=footer.163');">网易公司</a> <a href="http://www.youdao.com/terms/privacy.html" onmousedown="requestLog('FUNC_HIT','click=footer.privacy');">隐私政策</a> <a href="http://www.youdao.com/terms/index.html" onmousedown="requestLog('FUNC_HIT','click=footer.termindex');">服务条款</a> 京ICP证080268号 京公网安备110108003898号 </div>    </div></div><div id="snv" class="clear"><i><i></i></i></div><script type="text/javascript" src="http://shared.ydstatic.com/images/myth/js/index_min.js?201311221"></script><script type="text/javascript">(function (YD) {        var transData = function (data) {        var r = [], s = data.s, i = 0, l = s.length;        for (; i < l; i++) {            r.push({'c': s[i]});        }        return r;    };    var sug = YD.ui.suggest({        // source:"http://www.youdao.com/tglsuggest2/tglsuggest.s?keyfrom=web.index.suggest&o=" + .ns + "&rn=10&h=17&query="        source:"http://sug.so.360.cn/suggest/word?callback=YD.updateCall&encodein=utf-8&encodeout=utf-8&word="        ,menu: YD.cn("sg-wrap")[0], transData: transData    }, "query");})(getNS());</script></body></html>
【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/heyang78/p/3894063.html