標籤:
使用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)