Java:URLConnection访问网页

Java:URLConnection访问网页
参考:http://lamoop.diandian.com/post/2012-08-07/40032367973@import url(http://www.cppblog.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

示例:
package com.tur.demo;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Scanner;

public  class URLConnectionDemo {
     //  有道词典的在线查询功能.
     public  static  void query1()  throws Exception {
         //  如果URL有中文,则会出现乱码,这种情况需要用方法query2中的URLEncoder处理.
        URLConnection connection =  new URL(
                "http://fanyi.youdao.com/openapi.do?keyfrom=N3verL4nd&key=208118276&type=data&doctype=xml&version=1.1&q=investigate")
                .openConnection();
        InputStream response = connection.getInputStream();
        Scanner scanner =  new Scanner(response);

         while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
    }

     public  static  void query2()  throws Exception {
        String url = "http://fanyi.youdao.com/openapi.do";
        String charset = "UTF-8";
        String keyFrom = "N3verL4nd";
        String key = "208118276";
        String type = "data";
        String docType = "xml";
        String version = "1.1";
        String q = "中国";

        String query = String.format("keyfrom=%s&key=%s&type=%s&doctype=%s&version=%s&q=%s",
                URLEncoder.encode(keyFrom, charset),
                URLEncoder.encode(key, charset),
                URLEncoder.encode(type, charset),
                URLEncoder.encode(docType, charset),
                URLEncoder.encode(version, charset),
                URLEncoder.encode(q, charset));

        URLConnection connection =  new URL(url + "?" + query).openConnection();
        InputStream response = connection.getInputStream();
        Scanner scanner =  new Scanner(response);

         while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
    }

     public  static  void main(String[] args)  throws Exception {
        query1();
        query2();
    }
}

你可能感兴趣的:(Java:URLConnection访问网页)