首頁 收藏 QQ群
 網(wǎng)站導航

ZNDS智能電視網(wǎng) 推薦當貝市場

TV應用下載 / 資源分享區(qū)

軟件下載 | 游戲 | 討論 | 電視計算器

綜合交流 / 評測 / 活動區(qū)

交流區(qū) | 測硬件 | 網(wǎng)站活動 | Z幣中心

新手入門 / 進階 / 社區(qū)互助

新手 | 你問我答 | 免費刷機救磚 | ROM固件

查看: 13066|回復: 0
上一主題 下一主題
[教程]

第三十講:URLConnection和HttpClient使用入門

[復制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
發(fā)表于 2013-8-28 16:19 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
1791
本講內(nèi)容:URLConnection和HttpClient使用入門
在Android中除了使用WebView控件訪問網(wǎng)絡(luò)以外,還有用代碼方式訪問網(wǎng)絡(luò)的方法,代碼方式有時候會顯得更加靈活。本講會介紹使用URLConnection對象和HttpClient組件訪問網(wǎng)絡(luò)的方法。而這兩種方法和Java Web開發(fā)中的使用方式幾乎沒有區(qū)別,而Web開發(fā)的相關(guān)資料比比皆是,因此有興趣的同學學完本講之后可以專門去研究一下HttpClient4.0的內(nèi)容,以求更深入的學習。
一、分別使用URLConnection和HttpClient訪問Google天氣服務(wù)的例子
這個例子的的目的就是從Google哪里獲取鄭州的天氣預報信息,并顯示在TextView中,本講只會把返回的XML數(shù)據(jù)顯示出來,下一講我們學XML解析的時候再把這個天氣預報做成圖文并茂的形式,所以大家先暫時忍耐一下丑陋的界面。
1、新建一個項目 Lesson30_HttpClient ,主Activity的文件名是 MainActivity.java
2、res/layout/main.xml的內(nèi)容如下:
   
  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="網(wǎng)絡(luò)連接測試">   
       
    <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的內(nèi)容如下:
   
  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);   
       
                    // 設(shè)置按鈕單擊監(jiān)聽器   
                    b1.setOnClickListener(new View.OnClickListener() {   
                            @Override   
                            public void onClick(View v) {   
                                    // 使用URLConnection連接GoogleWeatherAPI   
                                    urlConn();   
                            }   
                    });   
       
                    // 設(shè)置按鈕單擊監(jiān)聽器   
                    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();   
                                    //設(shè)置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();   
                            //設(shè)置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中加入訪問網(wǎng)絡(luò)的權(quán)限,<uses-permission android:name="android.permission.INTERNET"></uses-permission>5、運行程序查看結(jié)果:      
按第一個按鈕的效果,返回的數(shù)據(jù)結(jié)果顯示在了TextView里。      
按第二個按鈕的效果,返回的數(shù)據(jù)結(jié)果顯示在了TextView里, 所不同的是顯示的是中文。好了,本講先到這里。   
   

上一篇:第八講:Intent入門指南
下一篇:第六講:用戶界面 View(二)
您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

Archiver|新帖|標簽|軟件|Sitemap|ZNDS智能電視網(wǎng) ( 蘇ICP備2023012627號 )

網(wǎng)絡(luò)信息服務(wù)信用承諾書 | 增值電信業(yè)務(wù)經(jīng)營許可證:蘇B2-20221768 丨 蘇公網(wǎng)安備 32011402011373號

GMT+8, 2024-10-21 05:58 , Processed in 0.057304 second(s), 14 queries , Redis On.

Powered by Discuz!

監(jiān)督舉報:report#znds.com (請將#替換為@)

© 2007-2024 ZNDS.Com

快速回復 返回頂部 返回列表