什麼是HTTP?1.超文字傳輸通訊協定 (HTTP)是互連網上應用最為廣泛的一種網路通訊協定2.HTTP是一個用戶端和伺服器端請求和應答的標準,用戶端是終端使用者,伺服器端是網站3.HTTP是用戶端瀏覽器或其他應用程式與Web伺服器之間的應用程式層通訊協定 HTTP工作原理1.用戶端與伺服器建立串連2.建立串連後,用戶端想伺服器端發送一個請求3.伺服器接收到請求之後,向用戶端發送響應資訊4.用戶端與伺服器端中斷連線注意:這裡的第四條需要注意,即當使用者看到如下的介面時,用戶端就已經與伺服器中斷連線了。 HTTP運行流程下面以一個簡單的例子介紹與伺服器端的串連,並從伺服器端擷取資料,是啟動並執行:當使用者點擊按鈕時,向伺服器端發送請求,並把返回的資料顯示在下面的textview中,下面是具體的實現代碼:[java] p<span style="font-size:18px;">ublic class MainActivity extends Activity { private Button button; private TextView textView; private HttpResponse httpResponse=null; private HttpEntity httpEntity=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button); textView=(TextView)findViewById(R.id.textview); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub //產生一個請求對象 HttpGet httpGet=new HttpGet("http://www.baidu.com"); //產生一個Http用戶端對象 HttpClient httpClient=new DefaultHttpClient(); //使用Http用戶端發送請求對象 InputStream inputStream=null; try { httpResponse=httpClient.execute(httpGet); //收到伺服器的響應之後把返回的資料讀取出來 httpEntity=httpResponse.getEntity(); inputStream=httpEntity.getContent(); //流檔案的讀取 BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); String resultString=""; String lineString=""; while((lineString=reader.readLine())!=null){ resultString=resultString+lineString; } textView.setText(resultString); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { inputStream.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } </span> 注意,由於涉及到網路連接,還要在AndroidManifest中聲明網路許可權: [html] <uses-permission android:name="android.permission.INTERNET"/>