Android 網路通訊、通訊

來源:互聯網
上載者:User

    網路操作是進行網路通訊的安卓程式必不可少的一個重要部分,Android平台有三種網路介面可以使用,他們分別是:java.net.*(標準Java介面)、Org.apache HttpComponents介面和Android.net.*(Android網路介面)。當然還可以使用瀏覽器webkit來進行網路訪問等。其中,前兩個介面可以用來進行http、socket通訊,後一個介面主要是用來判斷安卓裝置網路連接狀況的。所以,本節重點說一下前兩個介面。

   1、java.net.* HttpURLConnection介面

          此介面提供與連網有關的類,包括流和資料包通訊端、Internet協議、常見HTTP處理。如:建立URL以及URLConnection/HttpURLConnection對象、設定串連參數、串連伺服器、向伺服器寫資料、從伺服器讀取資料等通訊。下例為常見java.net包的Http例子: 

   

          HttpURLConnection是繼承於URLConnection類,二者都是抽象類別。其對象主要通過URL的openConnection方法獲得。建立方法如下代碼所示:

URL url = new URL("訪問的url");  HttpURLConnection conn=(HttpURLConnection)url.openConnection(); 

          通過以下方法可以對請求的屬性進行一些設定,如下所示:

//設定輸入和輸出資料流  conn.setDoOutput(true);  conn.setDoInput(true);  //佈建要求方式為POST  conn.setRequestMethod("POST");  //POST請求不能使用緩衝  urlConn.setUseCaches(false);  conn.connect();建立連結//關閉串連  conn.disConnection();  

           HttpURLConnection預設使用GET方式,例如下面代碼所示:

                               HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //使用HttpURLConnection開啟串連                  int nRC = http.getResponseCode();//得到串連狀態                if(nRC == HttpURLConnection.HTTP_OK){                InputStreamReader in = new InputStreamReader(urlConn.getInputStream());//得到讀取的內容(流)                    // 為輸出建立BufferedReader                  BufferedReader buffer = new BufferedReader(in);                  String inputLine = null;                  //使用迴圈來讀取獲得的資料                  while (((inputLine = buffer.readLine()) != null))                  {                      //我們在每一行後面加上一個"\n"來換行                      resultData += inputLine + "\n";                  }                           //關閉InputStreamReader                  }                             in.close();                  //關閉http串連                  conn.disconnect(); 

       如果需要使用POST方式,則需要setRequestMethod設定。代碼如下:   

        String httpUrl = "訪問的url";          //獲得的資料          String resultData = "";          URL url = null;          try         {              //構造一個URL對象              url = new URL(httpUrl);           }          catch (MalformedURLException e)          {              Log.e(DEBUG_TAG, "MalformedURLException");          }          if (url != null)          {              try             {                  // 使用HttpURLConnection開啟串連                  HttpURLConnection conn = (HttpURLConnection) url.openConnection();                  //因為這個是post請求,設立需要設定為true                  conn.setDoOutput(true);                  conn.setDoInput(true);                  // 設定以POST方式                  conn.setRequestMethod("POST");                  // Post 請求不能使用緩衝                  conn.setUseCaches(false);                  conn.setInstanceFollowRedirects(true);                  // 配置本次串連的Content-type,配置為application/x-www-form-urlencoded的                  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");                  // 串連,從postUrl.openConnection()至此的配置必須要在connect之前完成,                  // 要注意的是connection.getOutputStream會隱含的進行connect。                  conn.connect();                  //DataOutputStream流                  DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());                  //要上傳的參數                  String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");                  //將要上傳的內容寫入流中                  out.writeBytes(content);                   //重新整理、關閉                  out.flush();                  out.close();  

            也可以對其進行通用屬性的設定:

             // 設定通用的請求屬性           conn.setRequestProperty("accept", "*/*");           conn.setRequestProperty("connection", "Keep-Alive");           conn.setRequestProperty("user-agent",               "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");            // 建立實際的串連

   2、Apache Http Client

 

          Apache Http Client是一個開源項目,功能更加完善,為用戶端的Http編程提供高效、最新、功能豐富的工具包支援。它包含了get和post兩種請求方式,下面分別舉例:

          get方式:

    StringBuilder stringBuilder = new StringBuilder();HttpClient client = new DefaultHttpClient();HttpGet httpGet = new HttpGet(URL);try {HttpResponse response = client.execute(httpGet);StatusLine statusLine = response.getStatusLine();int statusCode = statusLine.getStatusCode();if (statusCode == 200) {HttpEntity entity = response.getEntity();if(entity!=null){                                    InputStream content = entity.getContent();BufferedReader reader = new BufferedReader(new InputStreamReader(content));String line;while ((line = reader.readLine()) != null) {stringBuilder.append(line);}}else{                                   Log.e("JSON", "Failed to download file");}} else {Log.e("JSON", "Failed to download file");}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return stringBuilder.toString();

    post方式:使用post方法進行參數傳遞時,需要使用NameValuePair來儲存要傳遞的參數。另外,還需要設定所使用的字元集。代碼如下所示:

        String httpUrl = "http://192.168.1.110:8080/httppost";          //HttpPost連線物件          HttpPost httpRequest = new HttpPost(httpUrl);          //使用NameValuePair來儲存要傳遞的Post參數          List<NameValuePair> params = new ArrayList<NameValuePair>();          //添加要傳遞的參數          params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));          //設定字元集              HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");              //請求httpRequest              httpRequest.setEntity(httpentity);              //取得預設的HttpClient              HttpClient httpclient = new DefaultHttpClient();              //取得HttpResponse              HttpResponse httpResponse = httpclient.execute(httpRequest);              //HttpStatus.SC_OK表示串連成功              if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)              {                  String strResult = EntityUtils.toString(httpResponse.getEntity());                  mTextView.setText(strResult);              }              else             {                  mTextView.setText("請求錯誤!");              }          } 

    HttpClient實際上是對Java提供方法的一些封裝,在HttpURLConnection中的輸入輸出資料流操作,在這個介面中被統一封裝成了HttpPost(HttpGet)和HttpResponse,這樣,就減少了操作的繁瑣性。

    

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.