1.项目目录
2.TestGet.java
package testhttpget;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class TestGet {
public static void main(String[] args) {
//这儿有两种解决方法,1. ReadyByGet 前加static;2.把ReadByGet 移到TestGet类外
new ReadByGet().start();
}
static class ReadByGet extends Thread{
@Override
public void run() {
try {
//http://fanyi.youdao.com/openapi.do?keyfrom=JKXY-test&keyfrom=JKXY-test&key=343166845&type=data&doctype=xml&version=1.1&q=welcome为测试URL
URL url=new URL("http://fanyi.youdao.com/openapi.do?keyfrom=JKXY-test&keyfrom=JKXY-test&key=343166845&type=data&doctype=xml&version=1.1&q=welcome");
//使用openConnection()函数打开链接,读取网络数据
URLConnection connection=url.openConnection();
//接收返回值
InputStream is=connection.getInputStream();
//包装InputStream,字节流包装成字符流时手动编码为UTF-8
InputStreamReader isr=new InputStreamReader(is,"UTF-8");
//包装InputStreamReader
BufferedReader br=new BufferedReader(isr);
String line;
//如果line有内容,添加到StringBuilder
StringBuilder builder=new StringBuilder();
while ((line=br.readLine())!=null) {
builder.append(line);
}
//越晚开启,越先关闭
br.close();
isr.close();
is.close();
//将builder中的内容打印
System.out.println(builder.toString());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
}
3.代码执行截图
4.将console代码烤出,新建test.xml文件
ctrl+v-->Ctrl +A-->Ctrl+i-->Ctrl+s
test.xml
<?xml version="1.0" encoding="UTF-8"?>
<youdao-fanyi>
<errorCode>0</errorCode>
<query><![CDATA[welcome]]></query> <!-- 有道翻译 -->
<translation>
<paragraph><![CDATA[欢迎]]></paragraph>
</translation> <!-- 有道词典-基本词典 -->
<basic> <!-- 音标 -->
<phonetic><![CDATA[ˈwelkəm]]></phonetic> <!-- 美式音标 -->
<us-phonetic><![CDATA[ˈwelkəm]]></us-phonetic> <!-- 英式音标 -->
<uk-phonetic><![CDATA[ˈwelkəm]]></uk-phonetic> <!-- 基本释义 -->
<explains>
<ex><![CDATA[adj. 受欢迎的;令人愉快的;可随意的;尽管……好了]]></ex>
<ex><![CDATA[n. 欢迎;迎接;接受]]></ex>
<ex><![CDATA[v. 欢迎,迎接;迎新;乐于接受]]></ex>
<ex><![CDATA[int. 欢迎]]></ex>
<ex><![CDATA[n. (Welcome) (美、印)韦尔科姆(人名)]]></ex>
</explains>
</basic> <!-- 有道词典-网络释义 -->
<web>
<explain>
<key><![CDATA[Welcome]]></key>
<value>
<ex><![CDATA[欢迎]]></ex>
<ex><![CDATA[受欢迎的]]></ex>
<ex><![CDATA[欢迎光临]]></ex>
</value>
</explain>
<explain>
<key><![CDATA[welcome to]]></key>
<value>
<ex><![CDATA[欢迎到来]]></ex>
<ex><![CDATA[欢迎参加]]></ex>
<ex><![CDATA[欢迎到]]></ex>
</value>
</explain>
<explain>
<key><![CDATA[Welcome aboard]]></key>
<value>
<ex><![CDATA[欢迎登机]]></ex>
<ex><![CDATA[欢迎加入]]></ex>
<ex><![CDATA[请上船]]></ex>
</value>
</explain>
</web>
</youdao-fanyi>