import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class TestGet { public static void main(String[] args) { new ReadByGet().start(); } } class ReadByGet extends Thread{//也可以将此类放在TestGet类里,前加static即可不报错 @Override public void run() { try { URL url = new URL("http://fanyi.youdao.com/openapi.do?keyfrom=JKXY-nfhttp&key=1100319125&type=data&doctype=xml&version=1.1&q= Welcome"); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is,"UTF-8");//防止中文乱码 BufferedReader br = new BufferedReader(isr); String line; StringBuilder builder = new StringBuilder(); while ((line = br.readLine())!=null) { builder.append(line); } br.close();//关闭流,先打开的后关闭,后打开的先关闭 isr.close(); is.close(); System.out.println(builder.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-10-12 20:14:14