Android使用Http協議訪問網路——HttpConnection

來源:互聯網
上載者:User

標籤:

套路篇

使用HttpConnection訪問網路一般有如下的套路:

1.擷取到HttpConnection的執行個體,new出一個URL對象,並傳入目標的網址,然後調用一下openConnection()方法。

1 HttpURLConnection connection=null;2 URL url=new URL("http://www.baidu.com");3 connection=(HttpURLConnection)url.openConnection();

2.得到了HttpConnection的執行個體後,佈建要求所用的方法(GET:從伺服器擷取資料,POST:提交資料給伺服器)

connection.setRequestMethod("GET");或
connection.setRequestMethod("POST");

3.自由定製的環節(設定連線逾時,讀取的毫秒數,以及伺服器希望得到的訊息頭等)

 connection.setConnectTimeout(8000); connection.setReadTimeout(8000);

4.利用getInputStream()方法擷取伺服器的返回的輸入資料流,然後讀取

InputStream in=connection.getInputStream();//下面對擷取到的輸入資料流進行讀取BufferedReader bufr=new BufferedReader(new InputStreamReader(in));StringBuilder response=new StringBuilder();String line=null;while((line=bufr.readLine())!=null){          response.append(line);}

5.調用disconnect()方法將HTTP串連關閉掉

 if(connection!=null){     connection.disconnect(); }

實戰篇

建立一個Android工程

1.activity_main.xml(裡面有一個Button和一個TextView)

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <Button        android:id="@+id/send_request"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Send Request" />    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/response_text"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </ScrollView></LinearLayout>

2.MainActivity

import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    public static final int SHOW_RESPONSE=0;//用於更新操作    private Button sendRequest;    private TextView responseText;    //用於處理和發送訊息的Hander    private Handler handler=new Handler(){        public void handleMessage(Message msg){            //如果返現msg.what=SHOW_RESPONSE,則進行制定操作,如想進行其他動作,則在子線程裡將SHOW_RESPONSE改變            switch (msg.what){                case SHOW_RESPONSE:                    String response=(String)msg.obj;                    //進行UI操作,將結果顯示到介面上                    responseText.setText(response);            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sendRequest=(Button)findViewById(R.id.send_request);        responseText=(TextView)findViewById(R.id.response_text);        sendRequest.setOnClickListener(this);    }    @Override    public void onClick(View v) {        if(v.getId()==R.id.send_request){            sendRequestWithHttpURLConnection();        }    }    private void sendRequestWithHttpURLConnection(){        //開啟線程來發起網路請求        new Thread(new Runnable() {            @Override            public void run() {                HttpURLConnection connection=null;                try{                    URL url=new URL("http://www.baidu.com");                    connection=(HttpURLConnection)url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    InputStream in=connection.getInputStream();                    //下面對擷取到的輸入資料流進行讀取                    BufferedReader bufr=new BufferedReader(new InputStreamReader(in));                    StringBuilder response=new StringBuilder();                    String line=null;                    while((line=bufr.readLine())!=null){                        response.append(line);                    }                    Message message=new Message();                    message.what=SHOW_RESPONSE;                    //將伺服器返回的資料存放到Message中                    message.obj=response.toString();                    handler.sendMessage(message);                }catch(Exception e){                    e.printStackTrace();                }finally {                    if(connection!=null){                        connection.disconnect();                    }                }            }        }).start();    }}

3.AndroidManifest.xml中註冊許可權

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

好,這個簡單的例子就弄完了,接下來就看看效果吧。

這樣我們就可以看到伺服器返回給我們的資料了。

Android使用Http協議訪問網路——HttpConnection

聯繫我們

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