Android:Http通訊協定

來源:互聯網
上載者:User

標籤:android   http   

    HTTP協議(HyperText Transfer Protocol,超文字傳輸通訊協定 (HTTP))是用於從WWW伺服器傳輸超文本到本地瀏覽器的傳送協議,它是基於TCP/IP協議的應用程式層協議。主要特點是:
1.支援客戶/伺服器模式。
2.簡單快速:客戶向伺服器請求服務時,只需傳送要求方法和路徑。要求方法常用的有GET、HEAD、POST。每種方法規定了客戶與伺服器聯絡的類型不同。由於HTTP協議簡單,使得HTTP伺服器的程式規模小,因而通訊速度很快。
3.靈活:HTTP允許傳輸任意類型的資料對象。正在傳輸的類型由Content-Type加以標記。
4.無串連:不需連線的含義是限制每次串連只處理一個請求。伺服器處理完客戶的請求,並收到客戶的應答後,即中斷連線。採用這種方式可以節省傳輸時間。
5.無狀態:HTTP協議是無狀態協議。無狀態是指協議對於交易處理沒有記憶能力。缺少狀態意味著如果後續處理需要前面的資訊,則它必須重傳,這樣可能導致每次串連傳送的資料量增大。另一方面,在伺服器不需要先前資訊時它的應答就較快。

    HTTP/1.1協議中共定義了八種方法(有時也叫“動作”)來表明Request-URI指定的資源的不同操作方式,其中最重要的兩種方法是:
1.GET方法 - 向特定的資源發出請求。
2.POST方法 - 向指定資源提交資料進行處理請求(例如提交表單或者上傳檔案),資料被包含在請求體中。

    Android系統中提供了三種通訊介面,其中Apache介面是較為常用的。

1.標準Java介面,java.net

2.標準Apache介面,org.apache.http

3.Android網路介面,android.net.http


執行個體一:使用Java介面的http進行網路通訊

①布局檔案,一個button,一個ImagevView,點擊button後從網路下載一張圖片顯示在ImageView上。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <Button        android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="點擊下載圖片" />    <ImageView        android:id="@+id/imageview"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_below="@+id/button" /></RelativeLayout>
②Activity

package com.example.httpgetdemo_apache;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends ActionBarActivity {private ImageView imageView;// 百度圖片上隨便找的一張圖片private static String URL_PATH = "http://pic002.cnblogs.com/images/2011/134595/2011031314373057.png";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) findViewById(R.id.imageview);Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub// 點擊button後啟動線程,因為主線程上不可以進行網路通訊new Thread(new MyThread()).start();}});}private class MyThread implements Runnable {@Overridepublic void run() {// TODO Auto-generated method stubURL url;try {// url指定為圖片地址url = new URL(URL_PATH);// 開啟網路連接HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 設定連線逾時時間。HttpUrlConnection對象還有其他的方法也是比較重要的,看下API。connection.setConnectTimeout(5000);// 獲得Http狀態代碼,200為OKint response = connection.getResponseCode();InputStream inputStream = null;if (response == 200) {System.out.println("串連成功");// 獲得輸入資料流inputStream = connection.getInputStream();} else {System.out.println("串連異常");}// 將輸入資料流轉化為Bitmap對象Bitmap bitmap = BitmapFactory.decodeStream(inputStream);// 通過handler處理來重新整理主線程Message message = Message.obtain();Bundle data = new Bundle();data.putParcelable("bitmap", bitmap);message.setData(data);handler.sendMessage(message);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// 通過handler處理來重新整理主線程private Handler handler = new Handler() {public void handleMessage(android.os.Message msg) {Bitmap bitmap = msg.getData().getParcelable("bitmap");imageView.setImageBitmap(bitmap);}};}

③添加網路許可權

<uses-permission android:name="android.permission.INTERNET"/>

執行個體二:使用Apache介面的http進行網路通訊

①和③和上面一致,直接修改Activity

package com.example.httpgetdemo_apache;import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends ActionBarActivity {private ImageView imageView;private static String URL_PATH = "http://pic002.cnblogs.com/images/2011/134595/2011031314373057.png";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView = (ImageView) findViewById(R.id.imageview);Button button = (Button) findViewById(R.id.button);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stub// new Thread(new MyThread()).start();// 使用非同步任務,其實他就是封裝好的Thread+Handlernew MyAsynTask().execute();}});}private class MyAsynTask extends AsyncTask<Void, Void, Bitmap> {@Overrideprotected Bitmap doInBackground(Void... arg0) {// TODO Auto-generated method stub// 基本上就按照以下流程走就是了// 執行個體化HttpClint對象HttpClient client = new DefaultHttpClient();// 執行個體化HttpGet對象,傳入URL地址HttpGet httpGet = new HttpGet(URL_PATH);Bitmap bitmap = null;try {// HttpClint對象的執行方法,參數常用HttpGet、HttpPost對象,// 返回HttpResponse對象,相當於上面的狀態代碼吧?HttpResponse response = client.execute(httpGet);// 通過HttpResponse對象得到實體物件,然後獲得輸入資料流,轉化為Bitmap對象HttpEntity entity = response.getEntity();InputStream inputStream = entity.getContent();bitmap = BitmapFactory.decodeStream(inputStream);} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bitmap;}@Overrideprotected void onPostExecute(Bitmap result) {// TODO Auto-generated method stub// 非同步任務就是後台執行完doInBackground方法後,返回一個值,然後onPostExecute方法做處理super.onPostExecute(result);// 將返回的Bitmap對象用來顯示ImageViewimageView.setImageBitmap(result);}}}

    以上兩個執行個體都是使用的Get方法。如果需要向伺服器提交資料,Get方法是將資料直接顯示地添加到url上,格式就是在原有的url基礎上添加?key1=value1&key2=value2;而Post方法在Apache介面中是在HttpPost對象中設定實體,其主要步驟是:

HttpPost httpPost = new HttpPost(URL_PATH);List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();nameValuePairs.add(new BasicNameValuePair("name1", "value1"));nameValuePairs.add(new BasicNameValuePair("name2", "value2"));HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);httpPost.setEntity(entity);
可以看出,使用Post方法提交資料是比Get方法安全的。由於自己不懂搭建伺服器,所以這個有點不好測試,先留個印象吧!


Android: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.