SDL: Replaced Apache HTTP with HttpURLConnection, to decrease app size and number of dependencies

This commit is contained in:
Sergii Pylypenko
2016-04-20 23:04:16 +03:00
parent 74e757be5c
commit 922feec8b9
4 changed files with 214 additions and 127 deletions

View File

@@ -31,16 +31,9 @@ import android.view.WindowManager;
import android.os.Environment;
import android.widget.TextView;
import org.apache.http.client.methods.*;
import org.apache.http.*;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.conn.*;
import org.apache.http.conn.params.*;
import org.apache.http.conn.scheme.*;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.*;
import java.security.SecureRandom;
import javax.net.ssl.HostnameVerifier;
@@ -301,8 +294,7 @@ class DataDownloader extends Thread
catch( FileNotFoundException e ) {}
catch( IOException e ) {};
HttpGet request;
HttpResponse response = null, responseError = null;
HttpURLConnection request = null;
long totalLen = 0;
long partialDownloadLen = 0;
CountingInputStream stream;
@@ -374,36 +366,43 @@ class DataDownloader extends Thread
else
{
Log.i("SDL", "Connecting to: " + url);
request = new HttpGet(url);
request.addHeader("Accept", "*/*");
if( partialDownloadLen > 0 ) {
request.addHeader("Range", "bytes=" + partialDownloadLen + "-");
Log.i("SDL", "Trying to resume download at pos " + partialDownloadLen);
}
try {
DefaultHttpClient client = HttpWithDisabledSslCertCheck();
client.getParams().setBooleanParameter("http.protocol.handle-redirects", true);
response = client.execute(request);
} catch (IOException e) {
Log.i("SDL", "Failed to connect to " + url);
};
if( response != null )
{
if( response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 206 )
request = (HttpURLConnection)(new URL(url).openConnection()); //new HttpGet(url);
while (true)
{
Log.i("SDL", "Failed to connect to " + url + " with error " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
responseError = response;
response = null;
downloadUrlIndex++;
continue;
request.setRequestProperty("Accept", "*/*");
request.setFollowRedirects(false);
if( partialDownloadLen > 0 )
{
request.setRequestProperty("Range", "bytes=" + partialDownloadLen + "-");
Log.i("SDL", "Trying to resume download at pos " + partialDownloadLen);
}
request.connect();
Log.i("SDL", "Got HTTP response " + request.getResponseCode() + " " + request.getResponseMessage() + " type " + request.getContentType() + " length " + request.getContentLength());
if (request.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP ||
request.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM ||
request.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER ||
request.getResponseCode() == 307 || request.getResponseCode() == 308)
{
String oldUrl = request.getURL().toString();
String cookie = request.getHeaderField("Set-Cookie");
request = (HttpURLConnection)(new URL(request.getHeaderField("Location")).openConnection());
Log.i("SDL", "Following HTTP redirect to " + request.getURL().toString());
//request.addRequestProperty("Referer", oldUrl);
//if (cookie != null)
// request.addRequestProperty("Cookie", cookie);
continue;
}
request.getInputStream();
break;
}
break;
}
else
{
} catch ( Exception e ) {
Log.i("SDL", "Failed to connect to " + url + " with error " + e.toString());
request = null;
downloadUrlIndex++;
continue;
}
break;
}
}
@@ -463,24 +462,24 @@ class DataDownloader extends Thread
}
else
{
if( response == null )
if( request == null )
{
Log.i("SDL", "Error connecting to " + url);
Status.setText( res.getString(R.string.failed_connecting_to, url) + (responseError == null ? "" : ": " + responseError.getStatusLine().getStatusCode() + " " + responseError.getStatusLine().getReasonPhrase()) );
Status.setText( res.getString(R.string.failed_connecting_to, url) );
return false;
}
Status.setText( downloadCount + "/" + downloadTotal + ": " + res.getString(R.string.dl_from, url) );
totalLen = response.getEntity().getContentLength();
totalLen = request.getContentLength();
try {
stream = new CountingInputStream(response.getEntity().getContent(), 8192);
stream = new CountingInputStream(request.getInputStream(), 8192);
} catch( java.io.IOException e ) {
Status.setText( res.getString(R.string.error_dl_from, url) );
return false;
}
}
if( !copyUnpackFileStream(stream, path, url, DoNotUnzip, FileInAssets, FileInExpansion, totalLen, partialDownloadLen, response, downloadCount, downloadTotal) )
if( !copyUnpackFileStream(stream, path, url, DoNotUnzip, FileInAssets, FileInExpansion, totalLen, partialDownloadLen, request, downloadCount, downloadTotal) )
return false;
OutputStream out = null;
@@ -515,7 +514,7 @@ class DataDownloader extends Thread
// Moved part of code to a separate method, because Android imposes a stupid limit on Java method size
private boolean copyUnpackFileStream( CountingInputStream stream, String path, String url,
boolean DoNotUnzip, boolean FileInAssets, boolean FileInExpansion,
long totalLen, long partialDownloadLen, HttpResponse response,
long totalLen, long partialDownloadLen, URLConnection response,
int downloadCount, int downloadTotal)
{
long updateStatusTime = 0;
@@ -536,11 +535,11 @@ class DataDownloader extends Thread
if( partialDownloadLen > 0 )
{
try {
Header[] range = response.getHeaders("Content-Range");
if( range.length > 0 && range[0].getValue().indexOf("bytes") == 0 )
String range = response.getHeaderField("Content-Range");
if( range != null && range.indexOf("bytes") == 0 )
{
//Log.i("SDL", "Resuming download of file '" + path + "': Content-Range: " + range[0].getValue());
String[] skippedBytes = range[0].getValue().split("/")[0].split("-")[0].split(" ");
String[] skippedBytes = range.split("/")[0].split("-")[0].split(" ");
if( skippedBytes.length >= 2 && Long.parseLong(skippedBytes[1]) == partialDownloadLen )
{
out = new FileOutputStream( path, true );
@@ -548,7 +547,7 @@ class DataDownloader extends Thread
}
}
else
Log.i("SDL", "Server does not support partial downloads. " + (range.length == 0 ? "" : range[0].getValue()));
Log.i("SDL", "Server does not support partial downloads. ");
} catch (Exception e) { }
}
if( out == null )
@@ -783,29 +782,6 @@ class DataDownloader extends Thread
Parent.getPackageName() + "/" + url.substring("obb:".length()) + "." + Parent.getPackageName() + ".obb";
}
private static DefaultHttpClient HttpWithDisabledSslCertCheck()
{
return new DefaultHttpClient();
// This code does not work
/*
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
return http;
*/
}
public class BackKeyListener implements MainActivity.KeyEventsListener
{
MainActivity p;