网络相关的工具类

package com.companyname.sdp.sce.tvappstore.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.util.InetAddressUtils;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.companyname.sdp.sce.tvappstore.constant.Constant;
import com.companyname.sdp.sce.tvappstore.log.ILog;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public final class Tools {
    public static final String TAG = "Tools";

    public static final String SD_CARD_PATH_APPSTORE = "appstore"
            + File.separator;

    public static final String SD_CARD_PATH_IMG_CACHE = SD_CARD_PATH_APPSTORE
            + "img" + File.separator;

    public static final int CONNECT_TIMEOUT = 30000;
    public static final int READ_TIMEOUT = 30000;

    public static final int BYTE = 1024;

    /**
     * 获得网络的json对象
     *
     * @param path
     *            网络json地址
     * @return JSONObject
     * @throws Exception
     */
    public static JSONObject getHttpJsonObject(String path) throws Exception {
        String json = "";
        HttpURLConnection conn = null;
        Log.v(TAG, "path=" + path);
        conn = getHttpUrlConn(path);
        conn.connect();
        if (200 == conn.getResponseCode()) {
            InputStream inStream = null;
            inStream = conn.getInputStream();
            byte[] data = null;
            data = Tools.readInputStream(inStream);
            if (conn != null) {
                conn.disconnect();
            }
            json = new String(data);
        }
        else{
            json = new String("{respseStatus:-1,respseDesc:failure,resultObject: null}");
        }
        if (conn != null) {
            conn.disconnect();
        }
        Log.d(TAG, "json=" + json);
        return new JSONObject(json);
    }

    /**
     * 发送数据
     *
     * @param path
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    public static boolean sendData(String path) throws MalformedURLException,
            IOException {
        boolean ret = false;
        HttpURLConnection conn = null;
        conn = getHttpUrlConn(path);
        conn.connect();
        if (200 == conn.getResponseCode()) {
            ret = true;
        }
        if (conn != null) {
            conn.disconnect();
        }
        return ret;
    }

    /**
     * 建立url连接
     *
     * @param path
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    public static HttpURLConnection getHttpUrlConn(String path)
            throws MalformedURLException, IOException {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setRequestMethod("GET");
        return conn;
    }

    /**
     * 发送数据到服务器
     *
     * @param path
     *            服务器地址
     * @param params
     *            内容参数
     * @return 结果标示
     */
    public static JSONObject sendPost(String path, List<NameValuePair> params) {
        JSONObject resObject = null;
        String strResult = null;
        // HttpPost连接对象
        HttpPost httpRequest = null;
        HttpEntity httpEntity = null;
        HttpClient httpClient = null;
        try {
            httpRequest = new HttpPost(path);
            httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
            // 请求httpRequest
            httpRequest.setEntity(httpEntity);
            // 取得HttpClient
            httpClient = CustomerHttpClient.getHttpClient();
            // 取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpRequest);
            // HttpStatus.SC_OK表示连接成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                strResult = EntityUtils.toString(httpResponse.getEntity());
                resObject = new JSONObject(strResult);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return resObject;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream
     *            输入流
     * @return
     * @throws IOException
     */
    private static byte[] readInputStream(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[Tools.BYTE];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 检查网络是否为空
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        final ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
            return false;
        }
        return true;
    }

    public static String getClientUpdateUrl(Context context) {
        String resultStr = "null";
        try {

            int osVersion = android.os.Build.VERSION.SDK_INT;
            ILog.dPrint(TAG, "osVersion " + osVersion);
            PackageInfo info;
            info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            String device = Build.DEVICE;
            String path = Constant.URLUtil.sAPP_CLIENT_UPDATE_CHECK
                    + "osVersion=" + osVersion + "&appStoreVersion="
                    + info.versionCode + "&clientModel=" + device;

            JSONObject retObj = Tools.getHttpJsonObject(path);
            ILog.dPrint(TAG, "retObj = " + retObj);
            if (retObj == null
                    || Constant.sFAILED == Integer.parseInt(retObj
                            .getString(Constant.sRESPSE_STATUS))) {
                return resultStr;
            }
            resultStr = retObj.getString(Constant.sRESULT_OBJECT);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 获取系统配置文件中属性值
     *
     * @param key
     * @param defaultvalue
     * @return
     */
    public static String getProperties(String key, String defaultvalue) {
        String Value = null;
        Class<?> systemPropertiesClass = null;
        Method method = null;
        try {
            systemPropertiesClass = Class
                    .forName("android.os.SystemProperties");
            Class<?> getType[] = new Class[2];
            getType[0] = String.class;
            getType[1] = String.class;
            method = systemPropertiesClass.getMethod("get", getType);
            Object arglist[] = new Object[2];
            arglist[0] = key;
            arglist[1] = defaultvalue;
            Object receiver = new Object();
            Object retVal = method.invoke(receiver, arglist);
            if (receiver != null) {
                Value = (String) retVal;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Value;
    }

    /**
     * 设置系统配置文件中属性值
     *
     * @param key
     * @param value
     * @return
     */
    public static void setProperties(String key, String value) {
        Class<?> systemPropertiesClass = null;
        Method method = null;
        try {
            systemPropertiesClass = Class
                    .forName("android.os.SystemProperties");
            Class<?> getType[] = new Class[2];
            getType[0] = String.class;
            getType[1] = String.class;
            method = systemPropertiesClass.getMethod("set", getType);
            Object arglist[] = new Object[2];
            arglist[0] = key;
            arglist[1] = value;
            Object receiver = new Object();
            method.invoke(receiver, arglist);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ap和有线同时存在,多个ip的情况下
     *
     * @return
     */
    private static String getLocalIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    Log.e("gdgfd", "1111111111 ip ==="+inetAddress.getHostAddress().toString());
                    if (!inetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(inetAddress
                                    .getHostAddress())) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ILog.ePrint("WifiPreference IpAddress", ex.toString());
        }
        return null;
    }

    public static String getMac() {
        String mac_s = "";
        try {
            byte[] mac;
            NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress
                    .getByName(getLocalIp()));
            mac = ne.getHardwareAddress();
            mac_s = byte2hex(mac);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mac_s;
    }

    public static String getMyMac() {
        String mac_s = "";
        try {
            mac_s = getProperties("persist.sys.eth_mac", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mac_s;
    }

    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer(b.length);
        String stmp = "";
        int len = b.length;
        for (int n = 0; n < len; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1) {
                hs.append("0");
                hs.append(stmp);
            } else {
                hs = hs.append(stmp);
            }
        }
        return String.valueOf(hs);
    }
    
    class GetLocalOrNetBitmap extends AsyncTask<String, String, Boolean>{

        @Override
        protected Boolean doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            return null;
        }
        
    }

    /**
     * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
     *
     * @param url
     * @param needCheckCache
     *            是否验证本地缓存
     * @return
     */
    public static Bitmap GetLocalOrNetBitmap(String url, String cachePath,
            boolean needCheckCache) {
        
        if (needCheckCache && checkCache(url, cachePath)) {
            return getCacheBitmap(url, cachePath);
        }

        String fileName = url.split("/")[url.split("/").length - 1];
        String cacheFileName = fileName.split("\\.")[0] + ".0";

        Log.e("909504", "save dir,cacheFileName: " + cachePath + ","
                + cacheFileName);
        Log.e("909504", "url: " + url);

        Bitmap bitmap = null;
        //InputStream in = null;
        //BufferedOutputStream out = null;
        try {
            //in = new BufferedInputStream(new URL(url).openStream(), 1024);
            //final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            //out = new BufferedOutputStream(dataStream, 1024);
            //copy(in, out);
            //out.flush();
            //byte[] data = dataStream.toByteArray();
            //byte[] data = getImage(url);
             BitmapFactory.Options options = new BitmapFactory.Options();
             options.inSampleSize = 2;
            //bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
            bitmap = BitmapFactory.decodeStream(getImageStream(url), null, options);
            

            // 将图片缓存, poster目录则不缓存
            if (cachePath.indexOf(Constant.POSTER) <=0) {
                File file = new File(cachePath, cacheFileName);// 保存文件,
                bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(
                        file));
            }

            //data = null;
            //in.close();
            //out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return bitmap;
    }
    
     /**
     * Get image from newwork
     * @param path The path of image
     * @return byte[]
     * @throws Exception
     */  
    public static byte[] getImage(String path) throws Exception{  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setConnectTimeout(5 * 1000);  
        conn.setRequestMethod("GET");  
        InputStream inStream = conn.getInputStream();  
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){  
            return readStream(inStream);  
        }  
        return null;  
    }  
    
    public static byte[] readStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1){  
            outStream.write(buffer, 0, len);  
        }  
        outStream.close();  
        inStream.close();  
        return outStream.toByteArray();  
    }
    
    /**
     * Get image from newwork
     * @param path The path of image
     * @return InputStream
     * @throws Exception
     */  
    public static InputStream getImageStream(String path) throws Exception{  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setConnectTimeout(8 * 1000);  
        conn.setRequestMethod("GET");  
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){  
            return conn.getInputStream();  
        }  
        return null;  
    }  

    /*
     * 检测本地/data/data/package/cache/...下是否有该图片
     *
     * @return true:存在 false:不存在
     */
    private static boolean checkCache(String url, String cachePath) {
        Log.d("909504", "start checkCache url = " + url);
        try {
            String fileName = url.split("/")[url.split("/").length - 1];
            String cacheFileName = fileName.split("\\.")[0] + ".0";

            //Log.e("909504", "checkCache url's cacheFileName= " + cacheFileName);

            File cacheFilePath = new File(cachePath);
            String[] posterArr = cacheFilePath.list(new FilenameFilter() {
                @Override
                public boolean accept(File parentFile, String fileName) {
                    return fileName.endsWith(".0");
                }
            });

            if(posterArr == null || posterArr.length == 0){
                return false;
            }
            List<String> posterList = Arrays.asList(posterArr);

            for (int i = 0; i < posterList.size(); i++) {
                //Log.e("909504", "posterList[" + i + "] = " + posterList.get(i));
            }

            Log.d("909504", "posterList.contains( " + cacheFileName + ") = "
                    + posterList.contains(cacheFileName));

            return posterList.contains(cacheFileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Log.e("909504", "end checkCache url = " + url);
        }

        return false;
    }

    /*
     * 获取/data/data/package/cache/...下的图片,并转化成bitmap
     */
    public static Bitmap getCacheBitmap(String url, String cachePath) {

        String fileName = url.split("/")[url.split("/").length - 1];
        String cacheFileName = fileName.split("\\.")[0] + ".0";

        // String posterUrl = "file://" + cachePath + File.separator
        // + cacheFileName;
        
        

        String path = cachePath + File.separator + cacheFileName;
        
        Log.e("909504", "getCacheBitmap path: " + path);

        File mfile = new File(path);
        if (mfile.exists()) {// 若该文件存在
            Bitmap bm = BitmapFactory.decodeFile(path);
            return bm;
        }

        return null;
    }

    private static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] b = new byte[1024];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值