Skip to content

Instantly share code, notes, and snippets.

@rmkrishna
Created August 11, 2017 09:46
Show Gist options
  • Save rmkrishna/a3640c9b6daeae3f981138b67d0eee7f to your computer and use it in GitHub Desktop.
Save rmkrishna/a3640c9b6daeae3f981138b67d0eee7f to your computer and use it in GitHub Desktop.
NetworkUtility class
package in.rmkrishna.util.network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* A utility class which you can use to determine the connectivity of the network.
*/
public class NetworkUtility {
private static final String TAG = NetworkUtility.class.getSimpleName();
private static final String EXTERNAL_SERVER_FOR_PING_TEST = "http://m.google.com";
private static final int CONNECTION_TIMEOUT = 10000; // 10 seconds
private static final int OPERATION_TIMEOUT = 30 * 1000;
private static final String UTF8_CHARSET = "UTF-8";
private static final String CONTENT_TYPE_HEADER = "Content-Type";
private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding";
public enum MKNetworkType {
/**
* No network
*/
TYPE_NONE,
/**
* Unknown
*/
TYPE_UNKNOWN,
/**
* WIFI
*/
TYPE_WIFI,
/**
* ETHERNET
*/
TYPE_ETHERNET,
/**
* GPRS
*/
TYPE_GPRS,
/**
* EDGE
*/
TYPE_EDGE,
/**
* 3G
*/
TYPE_3G,
/**
* 4G
*/
TYPE_4G
}
/**
* <p>
* Test if device is connected (without using Internet ping test) <br/>
* Notes: The network is connected doesn't mean the Internet is accessable.
* </p>
*
* @return true if connected
*/
public static boolean isNetworkConnected(Context context) {
ConnectivityManager connManager = getConnectivityManager(context);
if (connManager == null) {
return false;
}
NetworkInfo netInfo = connManager.getActiveNetworkInfo();
return isNetworkConnected(netInfo);
}
public static boolean isNetworkConnected(NetworkInfo netInfo) {
if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
return false;
}
return true;
}
/**
* @param context
*
* @return Object of NetworkInfo when there is an active network, otherwise return null.
*/
public static NetworkInfo getActivityNetworkInfo(Context context) {
if (context == null) {
return null;
}
ConnectivityManager connManager = getConnectivityManager(context);
if (connManager == null) {
return null;
}
return connManager.getActiveNetworkInfo();
}
/**
* <p>
* Test if WiFi is connected and really available (using Internet ping test).<br/>
* It is a blocking method (10 seconds), do not call it in UI thread.
* </p>
*
* @return true if connected
*/
public static boolean isWifiConnectedAndAvailable(Context context) {
ConnectivityManager connManager = getConnectivityManager(context);
if (connManager == null) {
return false;
}
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
return innerPingExternalServer();
}
return false;
}
/**
* <p>
* Test if device is connected to Internet and really available (using Internet ping test) <br/>
* It is a blocking method (10 seconds), do not call it in UI thread.
* </p>
*
* @return true if connected
*/
public static boolean isNetworkConnectedAndAvailable(Context context) {
ConnectivityManager connManager = getConnectivityManager(context);
NetworkInfo netInfo = connManager.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
return false;
}
return innerPingExternalServer();
}
/**
* Ping the external server. It is a blocking method (10 seconds), do not call it in UI thread.
*
* @return true if Internet is available
*/
private static boolean innerPingExternalServer() {
try {
Response response = getResponse(EXTERNAL_SERVER_FOR_PING_TEST, null, null);
if (response != null && response.responseCode == HttpURLConnection.HTTP_OK) {
return true;
}
} catch (Exception e) {
}
return false;
}
/**
* Inner helper method.
*
* @param context
*
* @return
*/
private static ConnectivityManager getConnectivityManager(Context context) {
if (context == null) {
return null;
}
ConnectivityManager connManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return connManager;
}
/**
* Return a human-readable name describe the type of the network, for example "WIFI" or
* "MOBILE".
*
* @return Returns null when encounter error.
*/
public static String getCurrentNetworkMode(Context context) {
if (context == null) {
return null;
}
ConnectivityManager connManager = getConnectivityManager(context);
if (connManager == null) {
return null;
}
NetworkInfo netInfo = connManager.getActiveNetworkInfo();
if (netInfo == null) {
return null;
} else {
return netInfo.getTypeName();
}
}
/**
* @param context
* @param netInfo
*
* @return The network type defined in MKNetworkType, or MKNetworkType.TYPE_NONE when
* parameter netInfo is null.
*/
public static MKNetworkType getNetworkTypefromInfo(Context context, NetworkInfo netInfo) {
MKNetworkType networkType = MKNetworkType.TYPE_GPRS; // the default value
if (context == null || netInfo == null) {
return MKNetworkType.TYPE_NONE;
}
switch (netInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
networkType = MKNetworkType.TYPE_WIFI;
break;
case ConnectivityManager.TYPE_MOBILE:
TelephonyManager tm;
tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int networkMobileType = tm.getNetworkType();
switch (networkMobileType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
networkType = MKNetworkType.TYPE_GPRS;
break;
case TelephonyManager.NETWORK_TYPE_EDGE:
networkType = MKNetworkType.TYPE_EDGE;
break;
case TelephonyManager.NETWORK_TYPE_LTE:
networkType = MKNetworkType.TYPE_4G;
break;
default:
networkType = MKNetworkType.TYPE_3G;
break;
}
break;
case ConnectivityManager.TYPE_ETHERNET:
networkType = MKNetworkType.TYPE_ETHERNET;
break;
default:
break;
}
return networkType;
}
public static class Response {
public String responseValue;
public int responseCode = 500;
public String errorMessage;
}
public static HttpURLConnection getHttpUrlConnection(String urlValue, String credentials, String outputText) {
return getHttpUrlConnection(urlValue, credentials, outputText, null);
}
public static HttpURLConnection getHttpUrlConnection(String urlValue, String credentials, String outputText, HashMap<String, String> headers) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlValue);
connection = (HttpURLConnection) url.openConnection();
if (url.getProtocol().equalsIgnoreCase("https")) {
if (true) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
} else {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}};
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, null);
// Create a connection from url
HttpsURLConnection urlConnection = (HttpsURLConnection) connection;
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
return true;
// return hv.verify("example.com", session);
}
};
urlConnection.setHostnameVerifier(hostnameVerifier);
}
}
if (TextUtils.isEmpty(outputText)) {
connection.setRequestMethod("GET");
} else {
connection.setDoOutput(true);
connection.setRequestMethod("POST");
}
connection.setRequestProperty(CONTENT_TYPE_HEADER, "application/json");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Accept", "application/json");
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> header : headers.entrySet()) {
connection.setRequestProperty(header.getKey(), header.getValue());
}
}
if (credentials != null) {
connection.setRequestProperty("Authorization",
createAuthenticationHeader(credentials));
}
if (!TextUtils.isEmpty(outputText)) {
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
}
connection.setConnectTimeout(OPERATION_TIMEOUT);
connection.setReadTimeout(OPERATION_TIMEOUT);
connection.connect();
if (!TextUtils.isEmpty(outputText)) {
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(outputText.getBytes());
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Already catching the first IOException so nothing
// to do here.
}
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return connection;
}
public static HttpURLConnection getPutHttpUrlConnection(String urlValue, String credentials, String outputText, HashMap<String, String> headers) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlValue);
connection = (HttpURLConnection) url.openConnection();
if (url.getProtocol().equalsIgnoreCase("https")) {
if (true) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
} else {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
}};
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, null);
// Create a connection from url
HttpsURLConnection urlConnection = (HttpsURLConnection) connection;
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
return true;
// return hv.verify("example.com", session);
}
};
urlConnection.setHostnameVerifier(hostnameVerifier);
}
}
connection.setRequestMethod("PUT");
connection.setRequestProperty(CONTENT_TYPE_HEADER, "application/json");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Accept", "application/json");
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> header : headers.entrySet()) {
connection.setRequestProperty(header.getKey(), header.getValue());
}
}
if (credentials != null) {
connection.setRequestProperty("Authorization",
createAuthenticationHeader(credentials));
}
if (!TextUtils.isEmpty(outputText)) {
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
}
connection.setConnectTimeout(OPERATION_TIMEOUT);
connection.setReadTimeout(OPERATION_TIMEOUT);
connection.connect();
if (!TextUtils.isEmpty(outputText)) {
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(outputText.getBytes());
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
// Already catching the first IOException so nothing
// to do here.
}
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return connection;
}
public static Response getResponse(String urlValue, String credentials, String outputText) {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return getResponse(urlValue, credentials, outputText, headers, false);
}
public static Response getPutResponse(String urlValue, String credentials, String outputText, HashMap<String, String> headers, boolean isGzipEnabled) {
Response responseObj = new Response();
if (isGzipEnabled) {
if (headers == null) {
headers = new HashMap<String, String>();
}
headers.put(ACCEPT_ENCODING_HEADER, "gzip");
}
try {
HttpURLConnection connection =
getPutHttpUrlConnection(urlValue, credentials, outputText, headers);
int responseCode = connection.getResponseCode();
responseObj.responseCode = responseCode;
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
// we will not get any response as success when we create new
// user.
responseObj.responseValue =
convertStreamToString(connection.getInputStream(), isGzipEnabled);
} else {
// Some other error check the error log
String error = convertStreamToString(connection.getErrorStream(), isGzipEnabled);
responseObj.errorMessage = error;
}
} catch (MalformedURLException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
return responseObj;
}
public static Response getResponse(String urlValue, String credentials, String outputText, HashMap<String, String> headers, boolean isGzipEnabled) {
Response responseObj = new Response();
if (isGzipEnabled) {
if (headers == null) {
headers = new HashMap<String, String>();
}
headers.put(ACCEPT_ENCODING_HEADER, "gzip");
}
try {
HttpURLConnection connection =
getHttpUrlConnection(urlValue, credentials, outputText, headers);
int responseCode = connection.getResponseCode();
responseObj.responseCode = responseCode;
if (responseCode == HttpURLConnection.HTTP_OK
|| responseCode == HttpURLConnection.HTTP_CREATED) {
responseObj.responseValue =
convertStreamToString(connection.getInputStream(), isGzipEnabled);
} else {
// Some other error check the error log
String error = convertStreamToString(connection.getErrorStream(), isGzipEnabled);
responseObj.errorMessage = error;
}
} catch (MalformedURLException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
return responseObj;
}
/**
* To convert input stream into string.
*
* @param is
* @param isGzipEnabled
*
* @return
*
* @throws IOException
*/
private static String convertStreamToString(InputStream is, boolean isGzipEnabled) throws IOException {
// Just return empty if we InputStream is null.
if (is == null) {
return "";
}
InputStream cleanedIs = is;
if (isGzipEnabled) {
cleanedIs = new GZIPInputStream(is);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(cleanedIs, UTF8_CHARSET));
StringBuilder sb = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
sb.append(line);
sb.append("\n");
}
return sb.toString();
} finally {
if (reader != null) {
reader.close();
}
cleanedIs.close();
if (isGzipEnabled) {
is.close();
}
}
}
/**
* To get the Basic Authentication string.
*
* @param credentials
*
* @return
*/
private static String createAuthenticationHeader(String credentials) {
return "Basic " + Base64
.encodeToString(credentials.getBytes(), Base64.NO_WRAP | Base64.URL_SAFE);
}
private static SSLSocketFactory sAllHostsValidSocketFactory;
private static SSLSocketFactory getAllHostsValidSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
if (sAllHostsValidSocketFactory == null) {
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
sAllHostsValidSocketFactory = sc.getSocketFactory();
}
return sAllHostsValidSocketFactory;
}
private static HostnameVerifier sAllHostsValidVerifier;
private static HostnameVerifier getAllHostsValidVerifier() {
if (sAllHostsValidVerifier == null) {
sAllHostsValidVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}
return sAllHostsValidVerifier;
}
}
For Get request
NetworkUtility.Response response = NetworkUtility.getResponse(BASE_URL + query, null, null, header, false);
-----------------------------
For Post Request:
HashMap<String, String> header = new HashMap<>();
header.put("Checksum", emailSha1);
JSONObject jsonObject = new JSONObject();
jsonObject.put("email", email);
jsonObject.put("password", password);
String params = jsonObject.toString();
or
String params = "email="+email +"&password="+password;
NetworkUtility.Response response = NetworkUtility.getResponse(BASE_URL + query, [crentials if you want to send any], params, header(optional in HashMap<>), false);
--------------
@nabeelnazir163
Copy link

can you send me your email
I will you my java file
so see that file and let me know how to resolve that problem
Actually i want to upload an image to a web server but i can do that because of deprecate httpClient e.t.c
myEmailid : nabeeelnazir163@yahoo.com

@rmkrishna
Copy link
Author

@nabeelnazir163 Uploading image we should use Multipart, anyway I will try to send you an email both this connection class and Multipart.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment