URL类

public static void main(String[] args) throws MalformedURLException {
        BufferedReader in = null;
        String result = null;
        try {
            URL url = new URL("http://www.baidu.com");
            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String str = null;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
            result = sb.toString();
            System.out.println(result);
        } catch (Exception ex) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


返回的是:
<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css>
<
title>百度一下,你就知道</title>
</
head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span>

</form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script>

<a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>
三种连接方法:
            // 方法一   
           URL url = new URL("http://www.sina.com.cn");  
           URLConnection urlcon = url.openConnection();  
           InputStream is = urlcon.getInputStream();  
            
            // 方法二  
           URL url = new URL("http://www.yhfund.com.cn");  
           HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();  
           InputStream is = urlcon.getInputStream();  
            
           //方法三  
           URL url = new URL("http://www.yhfund.com.cn");  
           InputStream is = url.openStream();  

 

 

 
 /**
     * 调用数据同步
     * @param date 当前日期 格式yyyy-MM-dd
     * @param totalExclusion 传入“”字符串
     * @return 返回结果
     */
    public static String queryDataSynStatus(String date, String totalExclusion) {
        try {
            System.out.println("Data Collection Date: " + date);
            if (date == null)
                return "Data Synchronized Failure!";
            System.out.println("Data Synchronized Start!");
            String local = "http://localhost:7070/a/b.do";

            HashMap<String, String> params = new HashMap<String, String>();

            params.put("date", date);
            params.put("totalExclusion", totalExclusion);

            StringBuffer sb = new StringBuffer();
            for (String key : params.keySet()) {
                sb.append(key).append("=")
                        .append(params.get(key) != null ? params.get(key) : "")
                        .append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            // 新增接口
            String param = HttpRequest.sendPost(local, sb.toString());
            System.out.println(param);
            System.out.println("Data Synchronized End!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Data Synchronized Successfully!";
    }


 /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();


            conn.setRequestProperty("Host", "www.baidu.com");
            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setRequestProperty("Content-Length", "37");
            conn.setRequestProperty("Cookie", "JSESSIONID=************************");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Pragma", "no-cache");
            conn.setRequestProperty("Cache-Control", "no-cache");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

 


 

posted @ 2017-08-14 11:20  kasher  阅读(800)  评论(0编辑  收藏  举报