/**
* 打开一个Http连接,失败则返回null
*
* @param msg
* @param proxy
* @return
*/
private HttpURLConnection getConnection(HttpMsg msg) throws Throwable {
String url = msg.getUrl();
HttpURLConnection conn = null;
String defaultHost = Proxy.getDefaultHost();
int defaultPort = Proxy.getDefaultPort();
URL hostUrl = null;

ConnectivityManager connectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
int type = -1;
if(activeNetworkInfo!=null){
type = activeNetworkInfo.getType();
}
String exrea = activeNetworkInfo.getExtraInfo();

//wap
if(type == ConnectivityManager.TYPE_MOBILE
&& (exrea != null && exrea.endsWith("wap")) && defaultHost != null
&& defaultPort > 0){

String host = null;
String path = null;
int hostIndex = " http://".length();
int pathIndex = url.indexOf('/', hostIndex);
if (pathIndex < 0) {
host = url.substring(hostIndex);
path = "";
} else {
host = url.substring(hostIndex, pathIndex);
path = url.substring(pathIndex);
}
hostUrl = new URL("http://" + defaultHost + ":" + defaultPort
+ path);
conn = (HttpURLConnection) hostUrl.openConnection();
conn.setRequestProperty("X-Online-Host", host);

}
//某些机型extra会有null情况 并且有代理
else if ((type == ConnectivityManager.TYPE_MOBILE) && exrea == null && defaultHost != null && defaultPort > 0)
{
java.net.Proxy proxy = new java.net.Proxy(Type.HTTP, new InetSocketAddress(defaultHost, defaultPort));
URL proxyURL = new URL(url);
conn = (HttpURLConnection) proxyURL.openConnection(proxy);
}
else {

hostUrl = new URL(url);
conn = (HttpURLConnection) hostUrl.openConnection();
}
conn.setConnectTimeout(10000);
conn.setInstanceFollowRedirects(msg.isInstanceFollowRedirects());
Enumeration enu = msg.requestProperty.keys();
String key;
String value;
while (enu.hasMoreElements()) {
key = (String) enu.nextElement();
value = (String) msg.requestProperty.get(key);
conn.setRequestProperty(key, value);
}
return conn;
}

更多相关文章

  1. 如何检查 Android 应用的内存使用情况
  2. Android推流帧率的设定与实际情况的影响
  3. 针对文件转移情况的Android SDK离线安装方法
  4. Android,关于设备独立像素(dip/dp),关于机型屏幕适配
  5. Android 拍照和图库功能(适配Android 6.0和7.0系统和华为机型问题

随机推荐

  1. Android(安卓)图片如何高效加载与缓存 (4
  2. android APP上线前,应该准备的东西
  3. 面面具到!android重力传感器
  4. Win10 Linux子系统编译Android系统源码
  5. Android:Service生命周期方法与Service启
  6. 刷机总结(阿里云os-->android4.2.2)注明:本
  7. Xamarin.Android-捕获未处理异常(全局异常
  8. Android(安卓)VR Player(全景视频播放器) [
  9. Android下的微博(新浪)-->第一步获取未授权
  10. 封闭与开放?乔布斯对Android的口水战