android createConnection
1512 ワード
public static HttpURLConnection createConnection(Context context, URL url){
HttpURLConnection connection = null;
try
{
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if ((wifiInfo.isAvailable()) && (wifiInfo.isConnected()))
{
connection = (HttpURLConnection)url.openConnection();
return connection;
}
NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobileInfo != null) && (mobileInfo.isAvailable()) && (mobileInfo.isConnected()))
{
Log.d("net", "connect by mobile");
String str = android.net.Proxy.getDefaultHost();
if (str != null)
{
java.net.Proxy proxy = new java.net.Proxy(Proxy.Type.HTTP, new InetSocketAddress(android.net.Proxy.getDefaultHost(), android.net.Proxy.getDefaultPort()));
connection = (HttpURLConnection)url.openConnection(proxy);
return connection;
}
return (HttpURLConnection)url.openConnection();
}
Log.d("net", "connect by other");
return (HttpURLConnection)url.openConnection();
}
catch (Exception localException)
{
localException.printStackTrace();
Log.d("net", "connect errpr");
connection = null;
}
return connection;
}
Androidネットワーク環境に応じたConnectionの作成