網絡連接——HttpURLConnection

在Android上發送HTTP請求的方式一般有兩種,HttpURLConnection和HttpClient
首先搭建一個簡單的界面

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button_sendrequest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="連接網絡"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/text_response"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

這裏使用了一個新的控件,ScrollView,由於手機屏幕有限,內容過多是放不下的,ScrollView可以以滾動的方式查看屏幕外的那部分內容。佈局中的一個按鈕用來點擊發送HTTP請求,TextView用來將服務器返回的數據顯示出來。
然後在主活動中進行點擊事件發送請求等的定義

package com.example.administrator.myhttpconnection;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity implements View.OnClickListener{
    private Button mButtonSendRequest;
    private TextView mTextview;
    public static final int SEND_MESSAGE=123;
    private Handler handle=new Handler(){
        @Override
        public void handleMessage(Message msg) {
        switch (msg.what){
            case SEND_MESSAGE:
                String response= (String) msg.obj;
                //在這裏進行UI操作,將內容顯示
                mTextview.setText(response);
                break;
            default:
                break;
        }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonSendRequest= (Button) findViewById(R.id.button_sendrequest);
        mButtonSendRequest.setOnClickListener(this);
        mTextview= (TextView) findViewById(R.id.text_response);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_sendrequest:
                //用一個新的子線程來進行發送HTTP請求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        connectInternet();
                    }
                }).start();

                break;
        }
    }

    private void connectInternet() {
        HttpURLConnection connection=null;
        try {
            URL url=new URL("http://localhost:8080/MyFirstWeb/MyServerletTest");
            //new一個URL的對象
            connection= (HttpURLConnection) url.openConnection();
            InputStream inputStream=connection.getInputStream();
            BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer response=new StringBuffer();
            String s=reader.readLine();
            while (s!=null){
               s=reader.readLine();
               response.append(s);
            }
            //由於子線程不允許進行UI操作,爲了將服務器返回的信息顯示出來,這裏使用Handler異步消息處理機制
            Message message=handle.obtainMessage();
            message.what=SEND_MESSAGE;
            message.obj=response.toString();
            handle.sendMessage(message);
            inputStream.close();
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }
}

在點擊事件裏新建一個子線程,用來發送HTTP請求,然後使用BufferedReader對服務器返回的流進行讀取,並將結果放在Message對象中,使用hadler發送,在handMessage中對這個Message進行處理,將其結果顯示到TextView中。
最重要的一點,由於是訪問網絡,所以需要權限,在Manifest中完善代碼

   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章