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

来源:互联网 发布:如何解读融资融券数据 编辑:程序博客网 时间:2024/04/30 16:13
1、新建android项目</span>
2、在xml文件中添加一个button:
<Button  android:id="@+id/httpGetButton"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:text="读取数据"/>

3、在Activity中为按钮添加监听事件(android在用http通信时会比较耗时,用AsyncTask处理):
findViewById(R.id.httpGetButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AsyncTask<String, Void, Void>(){
@Override
protected Void doInBackground(String... params) {
try {
<pre name="code" class="java" style="font-size: 14px; line-height: 25.200000762939453px;">URL <span style="font-family: 'Microsoft Yahei', Tahoma, Simsun;">url = new URL(params[0]);</span>
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute("http://fanyi.youdao.com/openapi.do?keyfrom=MyHttpGet1111222&key=1405130032&type=data&doctype=json&version=1.1&q=good");//传入URL,这里使用有道翻译提供的API
}
});
4、配置AndroidManifest.xml为项目添加网络链接:
<uses-permission android:name="android.permission.INTERNET"/>
5、运行程序查看logcat.
0 0
原创粉丝点击