1. 程式人生 > >Android使用Http協議訪問網路——HttpConnection

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

本文轉載自:https://www.cnblogs.com/Liang-Blog/p/5760201.html

套路篇

使用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)

<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">



    <Button
        android:id="@+id/sendRequest"
        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/responseText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</RelativeLayout>

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>

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

 

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