android HttpURLConnection conn = null; conn = getConnection(msg);
  lWCPViTfHaj4 2023年11月02日 17 0
/**

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

}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
lWCPViTfHaj4
最新推荐 更多