Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發之網絡部分

Android開發之網絡部分

編輯:關於Android編程

/**
*@author StormMaybin
*@Date 2016-09-1
*/

生命不息,奮斗不止!


WebView

對於,WebView 顧名思義,就是顯示各種各樣的網頁的控件,用法也相當簡單!


布局文件



    
        
    

MainActivity

package com.stormmaybin.webviewtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity
{

    private WebView webView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        initView();
        //設置webView支持js腳本
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading (WebView view, String url)
            {
                //根據傳入的參數加載新的網頁
                view.loadUrl(url);
                //表示當前webView可以處理打開新網頁的請求,不用借助系統浏覽器
                return true;
            }
        });
        webView.loadUrl("http://www.baidu.com");
    }
    public void initView ()
    {
        webView = (WebView) findViewById(R.id.webView);
    }
}

別往了申明訪問網絡權限

 

這樣一個WebView的例子就寫好了
這裡寫圖片描述


使用Http協議訪問網絡(HttpURLConnection)

Android 上發送HTTP請求方式一般有兩種,HttpURLConnection和HttpClient,對於HttpURLConnection:

首先要獲得一個HttpURLConnection的實例。

HttpURLConnection connection = (HttpURLConnection) new URL("url").openConnection();

這樣就得到一個HttpURLConnection對象,接下來要設置HTTP請求的所使用的方法,方法有兩個:”GET”和”POST”,GET表示希望從服務器端獲得數據,POST表示往服務器端發送數據!
connection.setRequestMethod("GET");
除此之外,還有兩個比較常用的HttpURLConnection方法,setConnectionTimeOut()連接超時設置和setReadTimeOut()讀取超時,參數都是毫秒數。getInputStream()是獲得服務器返回的輸入流,disconnect()是關閉連接!


布局文件




    

MainActivity

package com.stormmaybin.httpurlconnectiontest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
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 AppCompatActivity implements View.OnClickListener
{

    public static final int SHOW_RESPONSE = 0;
    private Button sendRequest = null;
    private TextView responseText = null;
    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            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);

        //初始化控件對象
        initView();
        //設置Button監聽事件
        sendRequest.setOnClickListener(this);
    }
    public void initView ()
    {
        sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response);
    }
    @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;
                    while ((line = bufr.readLine() )!= null)
                    {
                        response.append(line);
                    }

                    Message msg = new Message();
                    msg.what = SHOW_RESPONSE;
                    //將服務器返回的結果存到Msg中
                    msg.obj = response.toString();
                    //發送消息
                    handler.sendMessage(msg);
                }
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    //關閉資源
                    if (connection != null)
                    {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

權限申明

 

這裡寫圖片描述<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxociAvPg0KPGg0IGlkPQ=="使用http協議訪問網絡httpclient">使用Http協議訪問網絡(HttpClient)

HttpClient 是Apache 提供的一個HTTP網絡訪問接口,首先我們先要得到一個DefaultHttpClient 實例

HttpClient httpClient = new DefaultClient();

如果要發送一條GET請求,創建一個HttpGet對象,並傳入目標的網絡地址,然後調用HttpClient 的execute()方法

HttpGet httpGet = new HttpGet ("http://www.baidu.com");
httpClient.execute(httpGet);

發起一條POST

HttpPost httpPost = new HttpPost("http://www.baidu.com");
List params = new ArrayList();
params.add(new BasicNameValuePair("username","StormMa"));
params.add(new BasicNameValuePair("password","123456"));
UrlEncodeFormEnity enity = new UrlEncodeFormEnity(params, "utf-8");
httpPost.setEnity(enity);
httpClient.execute(httpPost);

執行完execute()方法之後會返回一個HttpResponse對象,這個對象包括了服務器返回的所有信息,如果狀態碼等於200說明請求響應成功了!

if (httpResponse.getStatusLine().getStatusCode == 200)

調用getEnity()方法獲得一個HttpEnity對象,然後調用EnityUtils.toString()這個靜態方法可以把HttpEnity轉換成字符串

HttpEnity enity = httpResponse.getEnity();
//utf-8是為了返回中文不產生亂碼
String response = EnityUtils.toString (enity, "utf-8");

布局文件



    

MainActivity

package com.stormmaybin.httpurlconnectiontest;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.ExpandedMenuView;
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 AppCompatActivity implements View.OnClickListener
{

    public static final int SHOW_RESPONSE = 0;
    private Button sendRequest = null;
    private TextView responseText = null;
    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            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);

        //初始化控件對象
        initView();
        //設置Button監聽事件
        sendRequest.setOnClickListener(this);
    }
    public void initView ()
    {
        sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response);
    }
    @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;
                    while ((line = bufr.readLine() )!= null)
                    {
                        response.append(line);
                    }

                    Message msg = new Message();
                    msg.what = SHOW_RESPONSE;
                    //將服務器返回的結果存到Msg中
                    msg.obj = response.toString();
                    //發送消息
                    handler.sendMessage(msg);
                }
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    //關閉資源
                    if (connection != null)
                    {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved