逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::
参考: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();
    }
}
posted on 2013-08-07 20:54 逛奔的蜗牛 阅读(2236) 评论(0)  编辑 收藏 引用 所属分类: Java

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理