Android 網路編程 Socket Http

來源:互聯網
上載者:User

標籤:

在Android的網路通訊中,通常會使用Socket進行裝置間數的資料通訊,使用Http來對網路資料進行請求。
1、Socket(通訊端)

不管是有過Java開發經驗還是.NET開發經驗的同學都應該對Socket有或多或少的瞭解,常見的TCP或者UDP協議其實都是基於Socket來實現的。

Socket是用於描述網路上的一個裝置中的一個進程或者應用程式的,Socket由IP地址和連接埠號碼兩部分組成。IP地址用來定位裝置,連接埠號碼用來定位應用程式或者進程,比如我們常見的運行在80連接埠上的HTTP協議。Socket的常見格式為:192.168.1.1:1234。

那麼應用程式是如何通過Socket來與網路中的其他裝置進行通訊的呢?通常情況下,Socket通訊有兩部分,一部分為監聽的Server端,一部分為主動請求串連的Client端。Server端會一直監聽Socket中的連接埠直到有請求為止,當Client端對該連接埠進行串連請求時,Server端就給予應答並返回一個Socket對象,以後在Server端與Client端的資料交換就可以使用這個Socket來進行操作了。
2、Android中使用Socket進行資料交換

ServerSocket
  建立服務端(Server)時,需要使用ServerSocket對象,這個對象會自動對其建構函式中傳入的連接埠號碼進行監聽,並在收到串連請求後,使用ServerSocket.accept()方法返回一個串連的的Socket對象。這個方法並不需要我們像在.NET中那樣使用Start方法,它會自動進行監聽的。

Socket
  不管建立用戶端(Client)還是在進行其他資料交換方面的操作時,都需要使用Socket類。Socket類在進行初始化時需要出入Server端的IP地址和連接埠號碼,並返回串連到Server端的一個Socket對象,如果是串連失敗,那麼將返回異常。同ServerSocket,也是自動進行串連請求的。

,並返回串連到Server端的一個Socket對象,如果是串連失敗,那麼將返回異常。同ServerSocket,也是自動進行串連請求的。

通過上面兩個步驟後,Server端和Client端就可以串連起來了,但是僅僅串連起來是沒有任何作用的,資料交換才是我們的目的,這時候就需要用到IO流中的OutputStream類和InputStream類。
OutputStream——可寫流
  當應用程式需要對流進行資料寫操作時,可以使用Socket.getOutputStream()方法返回的資料流進行操作。
InputStream——可讀流

  當應用程式要從流中取出資料時,可以使用Socket.getInputStream()方法返回的資料流進行操作。

View Code  package LiB.Demo;  import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket;  public class SocketHelper {     private static ServerSocket serverSocket = null;     private static Socket client = null;     private final static int port = 9048;     private static BufferedReader br= null;      private static BufferedWriter bw = null;          /**      * 建立一個SocketServer對象用來建立伺服器      * @throws IOException */     public static void CreateServer() throws IOException     {         serverSocket = new ServerSocket(port,10);         System.out.println("start listening...");     }          /**      * 建立一個Socket對象用來串連SocketServer對象      * @param dstName Server對象的ip地址      * @return       * @throws IOException */     public static Socket CreateClient(String dstName) throws IOException     {         Socket socket = new Socket(dstName, port);         //Socket sockets = new Socket("192.168.8.12",port);         return socket;     }          /**      * 返回一個已經串連到伺服器上的Socket對象      * @throws IOException */     public static void GetClinetSocket() throws IOException     {         client = serverSocket.accept();         System.out.println("get a connected client");     }          /**      * 向socket對象所擷取的流中發送資料      * @param socket      * @param msg      * @throws IOException */     public static void SendMsg(Socket socket , String msg) throws IOException     {         bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));         bw.write(msg);         bw.flush();         bw.close();     }          /**      * 擷取socket物件流程中資料      * @param socket      * @param msg      * @return      * @throws IOException */     public static String ReceiveMsg(Socket socket, String msg) throws IOException     {         br = new BufferedReader(new InputStreamReader(socket.getInputStream()));         String receiveMsg = "Receive msg:"+ br.readLine();         br.close();         return receiveMsg;     }          /**      * 釋放socket對象      * @throws IOException */     public static void Close() throws IOException     {         if(client != null)         {             client.close();         }         if(serverSocket != null)         {             serverSocket.close();         }     } }
3、HTTP通訊
  在開始前先簡單介紹下HTTP協議中的兩種不同的請求方式——GET和POST。GET方式在進行資料請求時,會把資料附加到URL後面傳遞給伺服器,比如常見的:http://XXX.XXX.XXX/XX.aspx?id=1,POST方式則是將請求的資料放到HTTP要求標頭中,作為要求標頭的一部分傳入伺服器。所以,在進行HTTP編程前,首先要明確究竟使用的哪種方式進行資料請求的。
  在Android中,可以有兩種方式可以用來進行Http編程:1、HttpURLConnection;2、HttpClient。
HttpURLConnection
  HttpURLConnection是繼承自URLConnection的一個抽象類別,在HTTP編程時,來自HttpURLConnection的類是所有操作的基礎,擷取該對象的代碼如下:

View Code      public HttpURLConnection urlconn= null;     private void Init() throws IOException     {         if (urlStr=="")         {             urlStr="http://www.baidu.com";         }         URL url = new URL(urlStr);         //開啟一個URL所指向的Connection對象         urlconn = (HttpURLConnection)url.openConnection();     }
HttpURLConnection對網路資源的請求在預設情況下是使用GET方式的,所以當使用GET方式時,不需要我們做太多的工作:

View Code      public HttpURLConnection urlconn= null;     private void Init() throws IOException     {         if (urlStr=="")         {             urlStr="http://www.baidu.com";         }         URL url = new URL(urlStr);         //開啟一個URL所指向的Connection對象         urlconn = (HttpURLConnection)url.openConnection();     }     /**      * Http中的get請求,在Url中帶有請求的參數,請求的URL格式通常為:"http://XXX.XXXX.com/xx.aspx?param=value"      * 在android中預設的http請求為get方式      * @return      * @throws IOException */     public String HttpGetMethod() throws IOException     {         if(urlconn == null)         {             Init();         }         String result = StreamDeal(urlconn.getInputStream());         urlconn.disconnect();         return result;     }
當我們需要使用POST方式時,就需要使用setRequestMethod()來佈建要求方式了。

View Code      /**      * Http中的post請求,不在Url中附加任何參數,這些參數都會通過cookie或者session等其他方式以索引值對的形式key=value傳送到伺服器上,完成一次請求      * 請求的URL格式通常為:"http://XXX.XXXX.com/xx.aspx"      * @param param 請求的鍵名      * @param value 請求的資料值      * @throws IOException */     public String HttpPostMethod(String key,String value) throws IOException     {         if (urlconn==null)         {             Init();         }         //設定該URLConnection可讀         urlconn.setDoInput(true);         //設定該URLConnection可寫         urlconn.setDoOutput(true);         //使用POST方式來提交資料         urlconn.setRequestMethod("POST");         //不運行緩衝         urlconn.setUseCaches(false);         //當使用POST方式進行資料請求時,我們可以手動執行connect動作,當然,這個動作其實在getOutputStream()方法中會預設執行的 //上面那些設定URLConnection屬性的動作,一定要在connect動作執行前,因為一旦動作已經執行,熟悉設定就沒有任何作用了         urlconn.connect();         //使用POST方式時,我們需要自己構造部分Http請求的內容,因此我們需要使用OutputStream來進行資料寫如操作         OutputStreamWriter writer = new OutputStreamWriter(urlconn.getOutputStream());                  String urlQueryStr = key+"="+URLEncoder.encode(value, "Utf-8");         writer.write(urlQueryStr);                  writer.flush();         writer.close();         //擷取返回的內容         String result = StreamDeal(urlconn.getInputStream());         return result;              }
HttpClient
  這個類並不是來自Android的,而是來自org.apache.http。和HttpURLConnection相同,HttpClient也存在GET和POST兩種方式。
HttpGet
      在HttpClient中,我們可以非常便於使用HttpGet對象來通過GET方式進行資料請求操作,當獲得HttpGet對象後我們可以使用HttpClient的execute方法來向我們的伺服器發送請求。在發送的GET請求被伺服器相應後,會返回一個HttpResponse響應對象,利用這個響應的對象我們能夠獲得響應回來的狀態代碼,如:200、400、401等等。

View Code      public String HttpGetMethod()     {         String result = "";         try         {         HttpGet httpRequest = new HttpGet(urlStr);         HttpClient httpClient = new DefaultHttpClient();         HttpResponse httpResponse = httpClient.execute(httpRequest);         if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)         {             result = EntityUtils.toString(httpResponse.getEntity());         }         else         {             result = "null";         }         return result;         }         catch(Exception e)         {             return null;         }     }

HttpPost

      當我們使用POST方式時,我們可以使用HttpPost類來進行操作。當擷取了HttpPost對象後,我們就需要向這個請求體傳入鍵值對,這個鍵值對我們可以使用NameValuePair對象來進行構造,然後再使用HttpRequest對象最終構造我們的請求體,最後使用HttpClient的execute方法來發送我們的請求,並在得到響應後返回一個HttpResponse對象。其他動作和我們在HttpGet對象中的操作一樣。

View Code  public String HttpPostMethod(String key,String value)     {         String result = "";         try         {         // HttpPost連線物件         HttpPost httpRequest = new HttpPost(urlStr);         // 使用NameValuePair來儲存要傳遞的Post參數         List<NameValuePair> params = new ArrayList<NameValuePair>();         // 添加要傳遞的參數         params.add(new BasicNameValuePair(key, value));         // 設定字元集         HttpEntity httpentity = new UrlEncodedFormEntity(params, "Utf-8");         // 請求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) {             // 取得返回的字串             result = EntityUtils.toString(httpResponse.getEntity());             return result;          } else {              return "null";         }         }         catch(Exception e)         {             return null;         }     }






Android 網路編程 Socket Http

聯繫我們

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