android網路通訊(1)

來源:互聯網
上載者:User

標籤:

使用HttpURLConnecation 進行通訊

1、GET 請求:

new Thread(){public void run() {try{//1. 串連網路  建立URL對象URL url = new URL("http://www.baidu.com");//2.開啟串連  並獲得HttpURLConnection對象HttpURLConnection huc = (HttpURLConnection) url.openConnection();//3. 讀取該對象資源的資料 huc.setDoInput(true);// 設定讀取資料huc.setRequestMethod("GET");//佈建要求模式  GEThuc.connect();//建立連結成功//獲得讀取流InputStream is = huc.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));//4.擷取讀取到的字元資料  建立StringBuilder 對象StringBuilder sb = new StringBuilder();//5.讀取資料String line = "";while((line=br.readLine())!=null){sb.append(line+"\n"); //收集讀取到的資料}//獲得Message對象Message msg = Message.obtain();msg.obj = sb;msg.what = 1;hd.sendMessage(msg);} catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}}}.start();

 2、POST請求:

new Thread(){public void run(){try{// 1.擷取URL對象URL url = new URL("http://wwwtest.rupeng.cn:8888/QueryAvatarInfo.ashx");// 2.擷取HttpURLConnection 對象HttpURLConnection huc = (HttpURLConnection) url.openConnection();//3.設定 讀入與寫出huc.setDoInput(true); huc.setDoOutput(true);//4.設定 請求模式huc.setRequestMethod("POST");//5.擷取寫入流OutputStream os = huc.getOutputStream();os.write(("action=GetAllNames").getBytes());os.flush();// 6.連結huc.connect();//7.讀取返回資料InputStream is = huc.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));StringBuilder sb = new StringBuilder();String line="";while((line=br.readLine())!=null){sb.append(line+"\n");}Message msg = Message.obtain();msg.obj = sb;msg.what = 1;// 發送資料hd.sendMessage(msg);// 關閉資源is.close();br.close();os.close();} catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}};}.start();

 

 

使用HttpClient 進行通訊

GET

new Thread(){// 耗時操作public void run(){//1、建立HttpClient對象  HttpClient hc = new DefaultHttpClient();//2.佈建要求模式HttpGet hg = new HttpGet("http://www.baidu.com/");try{//3.用戶端執行 GET請求 獲得應答對象HttpResponse hr = hc.execute(hg);//4.通過應答對象獲得 實體資料對象HttpEntity he = hr.getEntity();//5.通過EntityUtils工具類解析資料String data = EntityUtils.toString(he,"UTF-8");// 通過Handler發送資料Message msg = Message.obtain();msg.obj = data;msg.what = 1;hd.sendMessage(msg);} catch (ClientProtocolException e){// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}}}.start();

  

 

android網路通訊(1)

聯繫我們

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