Android检查网络是否可用及上网请求

Android手机联网方式有以下几种,要适应所有的方式。

Wifi

cmnet

cmwap

wifi和cmnet连接上就可以用了, cmwap是通过移动代理上网的, 有代理服务。但是移动联通电信的代理IP和都不一样。


先检查网络是否可用及网络类型:

public static boolean isNetworkAvailable(Context ctx) {  
        boolean isConnection=false;
        try {   
            ConnectivityManager cm = (ConnectivityManager) ctx   
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            if(info != null ){
                String typeName = info.getTypeName().toLowerCase(); // WIFI/MOBILE   
                if(!typeName.equals("wifi")){
                    if(null != info.getExtraInfo() ){
                        String wap = info.getExtraInfo().toLowerCase();  
                        //3gnet/3gwap/uninet/uniwap/cmnet/cmwap/ctnet/ctwap
                        if(wap.endsWith("wap"))
                            isWap = true;
                    }
                }   
                proxy=getproxy(ctx);
                if(proxy != null && !typeName.equals("wifi"))
                    isWap =true;
                isConnection= info.isAvailable();
            }
        } catch (Exception e) {   
            e.printStackTrace();      
        }
       return isConnection;
    }  


设置HttpURLConnection连接参数

private static HttpURLConnection connectionNetWap(String nameUrl,String endUrl) throws IOException {
        HttpURLConnection connection = null;
        if(isWap){
            URL url =  new  URL("http://"+proxy+":80/"+endUrl);   //移动网关
            connection = (HttpURLConnection )url.openConnection();  
            connection.setRequestProperty("X-Online-Host",nameUrl);
            connection.setRequestProperty("Accept","*/*");   
        }else {
            URL url =  new URL(nameUrl+endUrl);   
            connection = (HttpURLConnection )url.openConnection();
        }
        return connection;
    }


使用

public static String sendPostRequest(HashMap<String ,Object> params,String strUrl)
    {
        String result = null;
        BufferedReader br = null;
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        InputStream instream = null;
        try
        {
            // 参数
            StringBuilder paraUrl = new StringBuilder();       
            int index=0;
            if(params != null && !params.isEmpty() ){
                     for(Iterator it=params.entrySet().iterator();it.hasNext();){
                             Map.Entry e=(Map.Entry) it.next();
                             if(index >0 )
                                 paraUrl.append("&");
                             paraUrl.append(e.getKey().toString());
                             paraUrl.append("=");
                             paraUrl.append(URLEncoder.encode(e.getValue().toString(), "utf-8"));
                             index++;
                     }
             }

//非WAP方式, 这样就可以了:
//            URL url = new URL(strUrl);
//            connection = (HttpURLConnection)url.openConnection();
//适应所有方式
            connection=connectionNetWap(serviceUrl,strUrl);//support wap and net

            
            // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
            connection.setDoOutput(true);
            // Read from the connection. Default is true.
            connection.setDoInput(true);
            // Set the post method. Default is GET
            connection.setRequestMethod("POST");
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            // URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
            connection.setInstanceFollowRedirects(true);
            // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
            // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
            // 要注意的是connection.getOutputStream会隐含的进行connect。
            connection.connect();
            out = new DataOutputStream(connection
                    .getOutputStream());
            // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
            out.writeBytes(paraUrl.toString());
            out.flush();
            StringBuilder sBuilder = new StringBuilder();
            //取得输入流,并使用Reader读取
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                instream=connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(instream, "utf-8");
                int ichar;  
 
                while ((ichar = isr.read()) != 0) {
                    sBuilder.append((char) ichar);
                }
 
                result = sBuilder.toString();
                //isr.close();
            }
        }
        catch(Exception e)
        {
            Log.d("HTTP",e.getMessage());
            LogMgr.getLogger(HttpUtil.class).warning(e.getMessage());
        }finally{
            if(null != connection)
                connection.disconnect();
            try{

                if(null != out)
                    out.close(); // flush and close
            }catch(IOException ioe){
                Log.d("HTTP",ioe.getMessage());
            }
        }
        return result;        
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值