使用 Http 的 Get 方式读取网络数据

作为移动平台的应用,一定避免不了与网络交换数据,不论是读取网页数据,还是调用API接口,都必须掌握Http通信技术

代码如下:

package zw1;

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 http {

public static void main(String[] args) {

new ReadByGet().start();
}
static class ReadByGet extends Thread{
public void run() {
try {
URL url = new URL("http://fanyi.youdao.com/openapi.do?keyfrom=lovezw&key=1096891857&type=data&doctype=xml&version=1.1&q=income");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) !=null) {
builder.append(line);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
System.out.println(builder.toString());


} catch (MalformedURLException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}

}
}

}

posted @ 2017-04-11 16:12  拂柳扬玉  阅读(915)  评论(0编辑  收藏  举报