HttpsURLConnection and intermittent connections
Try System.setProperty("http.keepAlive", "false");
before you do
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
I would be really happy if someone get benefited with below code which will be helpful for:
1)Using HttpUrlConnection for making simple request.
2)Using HttpsUrlConnection by trusting all certificate.
3)Using HttpsUrlConnection with custom certificate for secure call(Using .bks file)
----------------Call these methods as per your requirements--------------
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends AppCompatActivity {
TextView txtResult;
public static final String TAG = MainActivity.class.getName();
public static final String SERVER_AUTH_URL = "https://demo.your.secure.ulr"; //Https i.e. Secure request
String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtResult = (TextView)findViewById(R.id.txt_result);
AsyncRequest asyncRequest = new AsyncRequest();
asyncRequest.execute();
}
public class AsyncRequest extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params) {
//result = sendGETRequestHttp(); //HttpUrlConnection request
//result = sendGETRequestHttpsTrustAll(); //HttpsUrlConnection request, trust all built in certificate in device
result = sendGETRequestHttpsWithCertificate(MainActivity.this); //request for secure connection with custom certificate
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
txtResult.setText(result);
}
}
private String sendGETRequestHttp() { // String requestString (If have POST parameters)
DataInputStream dis = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://www.yoururl.com/"); //Simple HttpURLConnection request
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET"); //("POST");
//OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//out.write(requestString.getBytes());
//out.flush();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
dis = new DataInputStream(in);
int ch;
long len = urlConnection.getContentLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = dis.read()) != -1) {
messagebuffer.append((char) ch);
}
} else {
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return messagebuffer.toString();
}
private String sendGETRequestHttpsTrustAll() { // String requestString (If have POST parameters)
DataInputStream dis = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection urlConnection = null;
try {
URL url = new URL(SERVER_AUTH_URL); //("https://www.codeproject.com/");
//Connection port HTTPS
HttpsURLConnection urlHttpsConnection = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts(); //Trust all certificate
//Open Connection
urlHttpsConnection = (HttpsURLConnection) url.openConnection();
//Set Verifier
urlHttpsConnection.setHostnameVerifier(DO_NOT_VERIFY);
//Assigning value
urlConnection = urlHttpsConnection;
} else {
urlConnection = (HttpURLConnection) url.openConnection();
}
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET"); //("POST");
//OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//out.write(requestString.getBytes());
//out.flush();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
dis = new DataInputStream(in);
int ch;
long len = urlConnection.getContentLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = dis.read()) != -1) {
messagebuffer.append((char) ch);
}
} else {
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return messagebuffer.toString();
}
private static void trustAllHosts() {
X509TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{easyTrustManager};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
private String sendGETRequestHttpsWithCertificate(Context context){ // String requestString (If have POST parameters)
DataInputStream dis = null;
StringBuffer messagebuffer = new StringBuffer();
HttpsURLConnection urlConnection = null;
try{
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("BKS");
InputStream in = context.getResources().openRawResource(R.raw.yourtruststore); //.bks file in raw folder of resources
String keyPassword = "pass"; //Your Password for cetificate
ks.load(in, keyPassword);
in.close();
tmf.init(ks);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, tms, new java.security.SecureRandom());
sc.init(null, tmf.getTrustManagers(), null);
// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL(SERVER_AUTH_URL);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(sc.getSocketFactory());
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET"); //("POST");
//OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//out.write(requestString.getBytes());
//out.flush();
InputStream inStream = new BufferedInputStream(urlConnection.getInputStream());
dis = new DataInputStream(inStream);
int ch;
long len = urlConnection.getContentLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = dis.read()) != -1) {
messagebuffer.append((char) ch);
}
} else {
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
dis.close();
} catch (Exception e) {
Log.d(TAG,"Connection error = "+e.getMessage());
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return messagebuffer.toString();
}
}
HttpsURLConnection and intermittent connections
Try System.setProperty("http.keepAlive", "false");
before you do
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
Just a little addition to m6tt's answer above:
private static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (!Constants.SUPPORTS_FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
How to download file from HTTP url that redirects to HTTPS url on Android?
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
==============================================
JSONObject json = new JSONObject(readUrl("https://"+Globals._Gateway+"/Android/Service.svc/GetFile/"+Param));