文章一:

首先在,AndroidManifest.xml 中增加访问权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
然后在*.java中增加一个函数,如果不能访问连接,那么就退出,可以自己设置:
//检查当前网络连接
public void checkInternet()
{
ConnectivityManager cm=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info=cm.getActiveNetworkInfo();
if(info!=null&&info.isConnected())

{
//能连接Internet
return;
}
else
{
//不能连接到
DisplayToast("you get not connect to the Internet,please log!");
try {
this.wait(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.finish();
}
}
android 权限可以访问下面链接:

http://developer.android.com/reference/android/Manifest.permission.html


文章二: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;
}





更多相关文章

  1. Android(安卓)使用xliff 格式化字符串
  2. MUI移动开发框架——微信支付(android部分)
  3. Android选择图片的两种方式
  4. android 由于使用Intent传送敏感数据(username password)的安全性
  5. react中使用微信jssdk分享总结
  6. Android开发笔记——查询通话记录及短信记录
  7. Android(安卓)O上获取Adaptive Icon的Bitmap对象
  8. android中使用DisplayMetrics获取屏幕参数
  9. Appium服务器初始化参数(Capability)

随机推荐

  1. Android(安卓)之 Notification
  2. Android(安卓)Menu
  3. Android开发实例详解之IMF
  4. Android入门教程(四)之------Android工程
  5. 利用BLCR加快android的启动过程
  6. android 属性汇总
  7. Android总结篇系列:Android广播机制
  8. 【自定义控件系列四】android绘制实战(一
  9. Android(安卓)Touch事件传递机制
  10. Android(安卓)动画系列之自定义补间动画