1. 程式人生 > >網路連線的工具類

網路連線的工具類

網路連線的工具類(判斷是否有網)

package com.bwei.zhoukao3.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

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 HttpUtils {
//單例模式
private static HttpUtils httpUtils=new HttpUtils();
private HttpLoadLisener httpLoadLisener;

private HttpUtils(){
}
public static HttpUtils getHttpUtils(){
    if (httpUtils==null){
        httpUtils=new HttpUtils();
    }
    return httpUtils;
}
//get請求
public void get(String url){
  MyTask myTask=new MyTask();
  myTask.execute(url);
}
//AsyncTask
class MyTask extends AsyncTask<String,Void,String>{

    @Override
    protected String doInBackground(String... strings) {
        String url=strings[0];
        try {
            URL url1=new URL(url);
           HttpURLConnection con= (HttpURLConnection) url1.openConnection();
           con.setConnectTimeout(5000);
           if (con.getResponseCode()==200){
               InputStream stream = con.getInputStream();
               String json = inputStirng(stream);
               return json;
           }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        httpLoadLisener.loadSuccess(s);
    }
}
//介面以
public interface HttpLoadLisener{
    void loadSuccess(String json);
    void loadError(String error);
}
//設定介面回撥的方法
public void setOnHttpLoadLisener(HttpLoadLisener httpLoadLisener){
    this.httpLoadLisener=httpLoadLisener;
}
//將流轉化為json字串
public static String inputStirng(InputStream inputStream) throws IOException {
    InputStreamReader reader = new InputStreamReader(inputStream);
    char[] chars=new char[1024];
    int len=0;
    StringBuffer buffer=new StringBuffer();
    while ((len=reader.read(chars))!=-1){
        String s = new String(chars, 0, len);
        buffer.append(s);
    }
    return buffer.toString();
}
//判斷是否網路
public static boolean HasNet(Context context){
    ConnectivityManager conn= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conn!=null){
        NetworkInfo info = conn.getActiveNetworkInfo();
        if (info==null){
            return false;
        }else {
            return true;
        }
    }
    return false;
}

}