Android---网络请求

 2017-4-19 第一次更新
ConnectivityManager connManger = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

在ConnectivityManger对象中有一些相关的方法

        NetworkInfo[] infos = connManger.getAllNetworkInfo(); // 获取所有的连接对象信息
        NetworkInfo active_info = connManger.getActiveNetworkInfo(); // 获取可用的连接对象信息
        active_info.isAvailable(); // 可用
        active_info.isConnected(); // 已经连接
        active_info.isConnectedOrConnecting(); // 已经连接或正在连接
        // active_info.getState().CONNECTED;
        // active_info.getState().CONNECTING;
判断网络状态
  //判断网络是否可用
    public boolean isNetworkAvailable() {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                //当前网络是可用的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    //当前所连接的网路可用
                    Log.d(TAG, "网络状态:可用");
                    return true;
                }
            }
        }

        Log.d(TAG, "网络状态:不可用");
        return false;
    }

    //判断当前网络连接的类型信息
    public int getConnectedType() {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                //当前网络是可用的
                //返回网络类型
                Log.d(TAG, "网络类型:" + info.getType());
                return info.getType();
            }
        }
        Log.d(TAG, "网络类型:" + "-1");
        return -1;
    }

    //判断WIFI网络是否可用
    public boolean isWifiAvailable() {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo myWifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (myWifiInfo != null) {
                Log.d(TAG, "WIFI网络是否可用:可用");
                return myWifiInfo.isAvailable();
            }
        }

        Log.d(TAG, "WIFI网络是否可用:不可用");
        return false;
    }

    //判断MOBILE网络是否可用
    public boolean isMobileAvailable() {

        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo myMobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (myMobileInfo != null) {
                Log.d(TAG, "MOBILE网络是否可用:可用");
                return myMobileInfo.isAvailable();
            }
        }

        Log.d(TAG, "MOBILE网络是否可用:不可用");
        return false;
    }

}
进行网络连接请求
package com.example.asec;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**  * Created by hp- on 2017/4/19.  * 网络连接类  * myGet:从服务器获取数据  * myPost:提交数据给服务器  */  public class MyNetConnection {

    private static String TAG = MyNetConnection.class.getName();
    private String baseURL;//请求地址
    private String myData;//向服务器提交的数据
    private static String backMsg = null;//服务器返回数据,暂时没有方法返回这个值,只做打印

    //handler获取服务器返回值
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){//0--Get,1--Post
                case 0:
                    backMsg = (String) msg.obj;
                    break;
                case 1:
                    backMsg = (String) msg.obj;
                    break;
            }

        }
    };

    public MyNetConnection(String baseURL) {
        this.baseURL = baseURL;
    }

    public MyNetConnection(String baseURL, String myData) {
        this.baseURL = baseURL;
        this.myData = myData;
    }

    //发起Get请求
    public void myGet() {

        //开启线程发起Get请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(baseURL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    //对获取的服务器返回的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    backMsg = response.toString();
                    Log.d(TAG, "myGet---服务器返回值:" + backMsg);

                    //关掉资源
                    in.close();
                    reader.close();

                    //将服务器返回结果放在Message                    Message message = new Message();
                    message.what = 0;//0--Get,1--Post
                    message.obj = backMsg;
                    handler.sendMessage(message);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    connection.disconnect();
                }
            }

        }).start();


    }

    //发起Post请求,传值给服务器
    public void myPost() {

        //开启线程发起Post请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(baseURL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes(myData);

                    InputStream in = connection.getInputStream();
                    //对获取的服务器返回的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    backMsg = response.toString();
                    Log.d(TAG, "myPost---服务器返回值:" + backMsg);

                    //关掉资源
                    out.close();
                    reader.close();

                    //将服务器返回结果放在Message                    Message message = new Message();
                    message.what = 1;//0--Get,1--Post
                    message.obj = backMsg;
                    handler.sendMessage(message);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    connection.disconnect();
                }
            }
        }).start();

    }
}

你可能感兴趣的:(Android---网络请求)