ZNDS智能电视网 推荐当贝市场

TV应用下载 / 资源分享区

软件下载 | 游戏 | 讨论 | 电视计算器

综合交流 / 评测 / 活动区

交流区 | 测硬件 | 网站活动 | Z币中心

新手入门 / 进阶 / 社区互助

新手 | 你问我答 | 免费刷机救砖 | ROM固件

查看: 16216|回复: 0
上一主题 下一主题
[教程]

第三十讲:URLConnection和HttpClient使用入门

[复制链接]
跳转到指定楼层
楼主
发表于 2013-8-28 16:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
1791
本讲内容:URLConnection和HttpClient使用入门
在Android中除了使用WebView控件访问网络以外,还有用代码方式访问网络的方法,代码方式有时候会显得更加灵活。本讲会介绍使用URLConnection对象和HttpClient组件访问网络的方法。而这两种方法和Java Web开发中的使用方式几乎没有区别,而Web开发的相关资料比比皆是,因此有兴趣的同学学完本讲之后可以专门去研究一下HttpClient4.0的内容,以求更深入的学习。
一、分别使用URLConnection和HttpClient访问Google天气服务的例子
这个例子的的目的就是从Google哪里获取郑州的天气预报信息,并显示在TextView中,本讲只会把返回的XML数据显示出来,下一讲我们学XML解析的时候再把这个天气预报做成图文并茂的形式,所以大家先暂时忍耐一下丑陋的界面。
1、新建一个项目 Lesson30_HttpClient ,主Activity的文件名是 MainActivity.java
2、res/layout/main.xml的内容如下:
   
  1. <?xml version="1.0" encoding="utf-8"?>   
    <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">   
       
    <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/TextView01" android:text="网络连接测试">   
       
    <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/Button01" android:text="使用URLConnection访问GoogleWeatherAPI">   
    </button>   
       
    <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/Button02" android:text="使用HttpClient访问GoogleWeatherAPI">   
    </button>   
       
    <scrollview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ScrollView01">   
            <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView02">   
            </textview>   
    </scrollview>   
    </textview></linearlayout>
复制代码
3、MainActivity.java的内容如下:
   
  1. package android.basic.lesson30;   
       
    import java.io.InputStreamReader;   
    import java.net.HttpURLConnection;   
    import java.net.URL;   
       
    import org.apache.http.client.ResponseHandler;   
    import org.apache.http.client.methods.HttpGet;   
    import org.apache.http.impl.client.BasicResponseHandler;   
    import org.apache.http.impl.client.DefaultHttpClient;   
       
    import android.app.Activity;   
    import android.os.Bundle;   
    import android.view.View;   
    import android.widget.Button;   
    import android.widget.TextView;   
    import android.widget.Toast;   
       
    public class MainActivity extends Activity {   
       
            TextView tv;   
       
            String googleWeatherUrl1 = "http://www.google.com/ig/api?weather=zhengzhou";   
            String googleWeatherUrl2 = "http://www.google.com/ig/api?hl=zh-cn&weather=zhengzhou";   
       
            /** Called when the activity is first created. */   
            @Override   
            public void onCreate(Bundle savedInstanceState) {   
                    super.onCreate(savedInstanceState);   
                    setContentView(R.layout.main);   
       
                    // 定义UI组件   
                    Button b1 = (Button) findViewById(R.id.Button01);   
                    Button b2 = (Button) findViewById(R.id.Button02);   
                    tv = (TextView) findViewById(R.id.TextView02);   
       
                    // 设置按钮单击监听器   
                    b1.setOnClickListener(new View.OnClickListener() {   
                            @Override   
                            public void onClick(View v) {   
                                    // 使用URLConnection连接GoogleWeatherAPI   
                                    urlConn();   
                            }   
                    });   
       
                    // 设置按钮单击监听器   
                    b2.setOnClickListener(new View.OnClickListener() {   
                            @Override   
                            public void onClick(View v) {   
                                    // 使用HttpCient连接GoogleWeatherAPI   
                                    httpClientConn();   
       
                            }   
                    });   
       
            }   
       
            // 使用URLConnection连接GoogleWeatherAPI   
            protected void urlConn() {   
       
                    try {   
                            // URL   
                            URL url = new URL(googleWeatherUrl1);   
                            // HttpURLConnection   
                            HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();   
       
                            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {   
                                    Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",   
                                                    Toast.LENGTH_SHORT).show();   
                                    // InputStreamReader   
                                    InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");   
                                    int i;   
                                    String content = "";   
                                    // read   
                                    while ((i = isr.read()) != -1) {   
                                            content = content + (char) i;   
                                    }   
                                    isr.close();   
                                    //设置TextView   
                                    tv.setText(content);   
                            }   
                            //disconnect   
                            httpconn.disconnect();   
       
                    } catch (Exception e) {   
                            Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)   
                                            .show();   
                            e.printStackTrace();   
                    }   
            }   
       
            // 使用HttpCient连接GoogleWeatherAPI   
            protected void httpClientConn() {   
                    //DefaultHttpClient   
                    DefaultHttpClient httpclient = new DefaultHttpClient();   
                    //HttpGet   
                    HttpGet httpget = new HttpGet(googleWeatherUrl2);   
                    //ResponseHandler   
                    ResponseHandler<string> responseHandler = new BasicResponseHandler();   
       
                    try {   
                            String content = httpclient.execute(httpget, responseHandler);   
                            Toast.makeText(getApplicationContext(), "连接Google Weather API成功!",   
                                            Toast.LENGTH_SHORT).show();   
                            //设置TextView   
                            tv.setText(content);   
                    } catch (Exception e) {   
                            Toast.makeText(getApplicationContext(), "连接Google Weather API失败", Toast.LENGTH_SHORT)   
                            .show();   
                            e.printStackTrace();   
                    }   
                    httpclient.getConnectionManager().shutdown();   
            }   
    }</string>
复制代码
4、最后别忘了在AndroidManifest.xml中加入访问网络的权限,<uses-permission android:name="android.permission.INTERNET"></uses-permission>5、运行程序查看结果:      
按第一个按钮的效果,返回的数据结果显示在了TextView里。      
按第二个按钮的效果,返回的数据结果显示在了TextView里, 所不同的是显示的是中文。好了,本讲先到这里。   
   

上一篇:第八讲:Intent入门指南
下一篇:第六讲:用户界面 View(二)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

站长推荐 上一条 /1 下一条

Archiver|新帖|标签|软件|Sitemap|ZNDS智能电视网 ( 苏ICP备2023012627号 )

网络信息服务信用承诺书 | 增值电信业务经营许可证:苏B2-20221768 丨 苏公网安备 32011402011373号

GMT+8, 2025-8-2 03:56 , Processed in 0.056790 second(s), 14 queries , Redis On.

Powered by Discuz!

监督举报:report#znds.com (请将#替换为@)

© 2007-2025 ZNDS.Com

快速回复 返回顶部 返回列表