Android之Web通訊的使用

來源:互聯網
上載者:User

標籤:stack   zha   cli   timeout   system   mes   串連   rac   代碼   

一、瞭解Android網路基礎

  1、Android平台有三種網路介面可以使用

    a、標準Java介面 java.net.* 

    b、Apache介面 org.apache.*(開源項目HttpClient)

    c、Android網路介面 android.net.* 

二、掌握Android應用的HTTP通訊

  1、HTTP:超文字傳輸通訊協定 (HTTP)(Hyper Text Transfer Protocol)

  2、採用請求/響應模式

  3、Android提供了HttpURLConnection和HttpClient介面

三、HttpURLConnection介面

  1、HttpURLConnection是Java的標準類,繼承自URLConnection類。他們都是抽象類別無法執行個體化對象。

  a、主要是通過URL的openConnection方法獲得建立串連,代碼如下:

URL ur l= new URL(“http://www.google.com”); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

 

  b、預設使用Get方式,這需要通過url傳遞參數即可

URL url=new URL("http:www.google.com?parameter=bruce");HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();

  c、使用Post方式,則需要setRequestMethod設定

// 設定以POST方式urlConn.setRequestMethod("POST");//設定連線逾時時間,單位:毫秒urlConn.setConnectTimeout(10*1000);//設定讀取逾時時間,單位:毫秒urlConn.setReadTimeout(15*1000);//設定是否允許接收伺服器端響應內容,預設trueurlConn.setDoInput(true);//設定是否允許構建一個輸出資料流向伺服器傳遞資料,預設falseurlConn.setDoOutput(true);//設定是否使用緩衝,POST不能使用緩衝urlConn.useCache(false);//建立串連urlConn.connect();

  d、擷取網狀圖片,只需要將得到的資料流轉換成bitmap就可以了

//建立HttpURLConnection
HttpURLConnection conn=(HttpURLConnection)iamgeUrl.openConnection();
//設定是否允許接收伺服器端響應內容(預設為true)conn.setDoInput(true);
//建立串連conn.connect();
//構建輸入資料流InputStream stream=conn.getInputStream();
//將資料流轉換成Bitmapbitmap=BitmapFactory.decodeStream(stream);
//關閉流is.close();

 四、HttpClient

        一、Apache提供的HttpClient也適合我們在Android上開發互連網應用

    1、ClientConnectionManager介面

      a、用戶端串連管理的介面

    2、DefaultHttpClient

      a、預設的HTTP用戶端,可以使用建立HTTP串連

    3、HttpResponse

      a、一個Http串連響應,通過它可以得到返回的響應訊息

  二、實現步驟

    1、使用HttpClient需要以下五個步驟;

      a、使用DefaultHttpClient執行個體化HttpClient對象。

      b、建立HttpGet或HttpPost對象,將要請求的URL通過構造方法傳入HttpGet或HttpPost對象。

      c、調用execute方法發送HTTP GET或HTTP POST請求,並返回HttpResponse對象。

      d、通過HttpResponse介面的getEntity方法返迴響應資訊,並進行相應的處理。

      e、釋放串連。無論執行方法是否成功,都必須釋放串連。  

    2、使用Get方式提交請求

//HttpGet連線物件HttpGet httpRequest = new HttpGet(httpUrl);//取得HttpClient對象HttpClient httpclient = new DefaultHttpClient();//請求HttpClient,取得HttpResponseHttpResponse httpResponse = httpclient.execute(httpRequest);

    3、根據響應的代碼判斷請求是否成功

//請求成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){}

    4、代碼(GET)

//構建HttpClient的執行個體DefaultHttpClient httpClient=new DefaultHttpClient();//建立Get執行個體HttpGet get=new HttpGet("http://www.baidu.com");try{    //發送請求並得到響應結果    HttpResponse res=httpClient.execute(get);    //處理響應結果資料    if(res != null && res.getStatusLine().getStatusCode() == HttpStaatus.SC_OK){          System.out.println(EntityUtils.toString(res.getEmtity()));    } }catch(Exception ex){      ex.printStackTrace();      }finally{      //釋放資源      httpClient.getConnectionManager().shutdown();}    

    5、使用Post方式提交請求

//HttpPost連線物件HttpPost HTTPRequest=new HttpPost(httpUrl);

    6、使用NameValuePair來儲存要傳遞的參數

//使用NameValuePair來儲存要傳遞的Post參數List<NameValuePair>params=new ArrayList<NameValuePair>();//添加要傳遞的參數params.add(new BasicNameValuePair("pair","HttpClient_android_Post"));

    7、同樣是通過HTTP用戶端提交請求

//設定字元集HTTPEntity httpentity=new UrlEncodedFormEntity(params,"utf-8");//請求httpRequestHttpRequest.setEntity(httpentity);//取得預設的HttpClientHttpClient httpclient=new DefaultHttpClient();//提交請求httpclient.execute(httpRequest);

    8、代碼POST

//構建HttpClient執行個體DefaultHttpClient httpClient = new DefaultHttpClient();//建立Post執行個體HttpPost post = new HttpPost("http://www.baidu.com")//初始化請求參數List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("stuNo","123456"));params.add(new BasicNameValuePair("stuName","zhangsan"));params.add(new BasicNameValuePair("stuSex","男"));params.add(new BasicNameValuePair("stuTemp","1997-1-1"));params.add(new BasicNameValuePair("stuAddress","zhuhai"));try{     //佈建要求參數,並以UTF-8方式編碼     post.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));     //發送請求並得到響應結果     HttpResponse res=httpClient.execute(post);     //處理響應結果資料     if(res != null && res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){           System.out.println(EntityUtils.toString(res.getEntity()));       }}catch(Exception ex){      ex.printStackTrace();  }finally{      //釋放資源      httpClient.getConnectionManager().shutdown();}

    9、即時更新可以在用戶端通過線程不聽的請求並重新整理頁面

    10、不能直接線上程中更新UI,需要使用Handler來實現,代碼如下:

Handler mHandler=new Handler(){  public void handleMessage(Message msg){      super.handleMessage(msg);      //重新整理      refresh();    }  }

 

 

Android之Web通訊的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.