java http

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();
}
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章