现在的位置: 首页 > 综合 > 正文

android HttpURLConnection conn = null; conn = getConnection(msg);

2013年12月01日 ⁄ 综合 ⁄ 共 2003字 ⁄ 字号 评论关闭

 /**
     * 打开一个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;
    }

抱歉!评论已关闭.