Fixed http request crash

This commit is contained in:
2026-08-26 13:33:55 +02:00
parent 64936ce75a
commit 3f28e7b2bc
@@ -128,8 +128,8 @@ import eu.chainfire.libsuperuser.Shell;
public class Miscellaneous extends Service public class Miscellaneous extends Service
{ {
protected static String writeableFolderStringCache = null; protected static String writeableFolderStringCache = null;
protected final static String http_error_string = "HTTP_ERROR"; protected final static String http_error_string = "HTTP_ERROR";
protected final static String last_trigger_url_result_string = "last_trigger_url_result"; protected final static String last_trigger_url_result_string = "last_trigger_url_result";
protected final static String httpMainData = "httpMainData"; protected final static String httpMainData = "httpMainData";
protected final static String doNoEncodingString = "NoEncoding"; protected final static String doNoEncodingString = "NoEncoding";
protected final static String httpEncoding = "UTF-8"; protected final static String httpEncoding = "UTF-8";
@@ -164,14 +164,14 @@ public class Miscellaneous extends Service
StringBuilder responseBody = new StringBuilder(); StringBuilder responseBody = new StringBuilder();
boolean errorFound = false; boolean errorFound = false;
try try
{ {
try try
{ {
URL urlObject = new URL(url); URL urlObject = new URL(url);
HttpURLConnection connection; HttpURLConnection connection;
if(url.toLowerCase().contains("https")) if(url.toLowerCase().contains("https"))
{ {
connection = (HttpsURLConnection) urlObject.openConnection(); connection = (HttpsURLConnection) urlObject.openConnection();
if(Settings.httpAcceptAllCertificates) if(Settings.httpAcceptAllCertificates)
@@ -187,21 +187,21 @@ public class Miscellaneous extends Service
} }
} }
else else
connection = (HttpURLConnection) urlObject.openConnection(); connection = (HttpURLConnection) urlObject.openConnection();
// Add http simple authentication if specified // Add http simple authentication if specified
if(username != null && password != null) if(username != null && password != null)
{ {
String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT); String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT);
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encodedCredentials); connection.setRequestProperty ("Authorization", "Basic " + encodedCredentials);
} }
else if(method.equals(ActivityManageActionTriggerUrl.methodPost)) else if(method.equals(ActivityManageActionTriggerUrl.methodPost))
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
if(httpParams.size() > 0) if(httpParams != null && httpParams.size() > 0)
{ {
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
@@ -220,29 +220,29 @@ public class Miscellaneous extends Service
writer.close(); writer.close();
} }
InputStream content = (InputStream)connection.getInputStream(); InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content)); BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line; String line;
while ((line = in.readLine()) != null) while ((line = in.readLine()) != null)
responseBody.append(line + Miscellaneous.lineSeparator); responseBody.append(line + Miscellaneous.lineSeparator);
} }
catch(Exception e) catch(Exception e)
{ {
Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3); Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3);
errorFound = true; errorFound = true;
} }
} }
finally finally
{ {
// When HttpClient instance is no longer needed, // When HttpClient instance is no longer needed,
// shut down the connection manager to ensure // shut down the connection manager to ensure
// immediate deallocation of all system resources // immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown(); httpclient.getConnectionManager().shutdown();
if(errorFound) if(errorFound)
return http_error_string; return http_error_string;
else else
return responseBody.toString(); return responseBody.toString();
} }
} }
private static String getQuery(List<NameValuePair> params, String method) throws UnsupportedEncodingException private static String getQuery(List<NameValuePair> params, String method) throws UnsupportedEncodingException
@@ -299,31 +299,31 @@ public class Miscellaneous extends Service
public static String downloadUrlWithoutCertificateChecking(String url, String username, String password, String method, Map<String, String> httpParams) public static String downloadUrlWithoutCertificateChecking(String url, String username, String password, String method, Map<String, String> httpParams)
{ {
try try
{ {
HttpParams params = new BasicHttpParams(); HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params); HttpClient httpclient = new DefaultHttpClient(params);
httpclient = Actions.getInsecureSslClient(httpclient); httpclient = Actions.getInsecureSslClient(httpclient);
HttpRequestBase httpRequest; HttpRequestBase httpRequest;
if( if(
method.equals(ActivityManageActionTriggerUrl.methodPost) method.equals(ActivityManageActionTriggerUrl.methodPost)
|| ||
(username != null && password != null) (username != null && password != null)
|| ||
httpParams.size() > 0 httpParams.size() > 0
) )
httpRequest = new HttpPost(url); httpRequest = new HttpPost(url);
else else
httpRequest = new HttpGet(url); httpRequest = new HttpGet(url);
// Add http simple authentication if specified // Add http simple authentication if specified
if(username != null && password != null) if(username != null && password != null)
{ {
String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT); String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT);
httpRequest.addHeader("Authorization", "Basic " + encodedCredentials); httpRequest.addHeader("Authorization", "Basic " + encodedCredentials);
} }
if(httpParams.size() > 0) if(httpParams.size() > 0)
{ {
@@ -335,19 +335,19 @@ public class Miscellaneous extends Service
((HttpPost)httpRequest).setEntity(new UrlEncodedFormEntity(paramPairs, "UTF-8")); ((HttpPost)httpRequest).setEntity(new UrlEncodedFormEntity(paramPairs, "UTF-8"));
} }
HttpResponse response = httpclient.execute(httpRequest); HttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
if (entity != null) if (entity != null)
{ {
// System.out.println(EntityUtils.toString(entity)); // System.out.println(EntityUtils.toString(entity));
return EntityUtils.toString(entity); return EntityUtils.toString(entity);
} }
} }
catch(Exception e) catch(Exception e)
{ {
Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3); Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3);
return http_error_string; return http_error_string;
} }
// finally // finally
// { // {
// // When HttpClient instance is no longer needed, // // When HttpClient instance is no longer needed,
@@ -357,18 +357,18 @@ public class Miscellaneous extends Service
// return responseBody.toString(); // return responseBody.toString();
// } // }
return null; return null;
} }
public static int boolToInt(boolean input) public static int boolToInt(boolean input)
{ {
if(input) if(input)
return 1; return 1;
else else
return 0; return 0;
} }
@Override @Override
public IBinder onBind(Intent arg0) public IBinder onBind(Intent arg0)
{ {
return null; return null;
@@ -376,14 +376,14 @@ public class Miscellaneous extends Service
public static void logEvent(String type, String header, String description, int logLevel) public static void logEvent(String type, String header, String description, int logLevel)
{ {
try try
{ {
header = getAnyContext().getResources().getString(R.string.app_name); header = getAnyContext().getResources().getString(R.string.app_name);
} }
catch(NullPointerException e) catch(NullPointerException e)
{ {
header = "Automation"; header = "Automation";
} }
if(Settings.logToConsole) if(Settings.logToConsole)
{ {
@@ -411,19 +411,19 @@ public class Miscellaneous extends Service
protected static boolean logCleanerRunning = false; protected static boolean logCleanerRunning = false;
protected static void rotateLogFile(File logFile) protected static void rotateLogFile(File logFile)
{ {
logCleanerRunning = true; logCleanerRunning = true;
long maxSizeInBytes = (long)Settings.logFileMaxSize * 1024 * 1024; long maxSizeInBytes = (long)Settings.logFileMaxSize * 1024 * 1024;
if(logFile.exists() && logFile.length() > (maxSizeInBytes)) if(logFile.exists() && logFile.length() > (maxSizeInBytes))
{ {
Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file.", 3); Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file.", 3);
File archivedLogFile = new File(getWriteableFolder() + "/" + logFileName + "-old"); File archivedLogFile = new File(getWriteableFolder() + "/" + logFileName + "-old");
logFile.renameTo(archivedLogFile); logFile.renameTo(archivedLogFile);
Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file finished. Old log renamed to " + archivedLogFile.getAbsolutePath(), 3); Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file finished. Old log renamed to " + archivedLogFile.getAbsolutePath(), 3);
} }
logCleanerRunning = false; logCleanerRunning = false;
} }
protected static boolean testFolder(String folderPath) protected static boolean testFolder(String folderPath)
@@ -492,34 +492,34 @@ public class Miscellaneous extends Service
{ {
// if (testFolder(f)) // if (testFolder(f))
// { // {
String pathToUse = f + "/" + Settings.folderName; String pathToUse = f + "/" + Settings.folderName;
// Toast.makeText(getAnyContext(), "Using " + pathToUse + " to store settings and log.", Toast.LENGTH_LONG).show(); // Toast.makeText(getAnyContext(), "Using " + pathToUse + " to store settings and log.", Toast.LENGTH_LONG).show();
// Migrate existing files // Migrate existing files
File oldDirectory = new File(pathToUse); File oldDirectory = new File(pathToUse);
File newDirectory = new File(writeableFolderStringCache); File newDirectory = new File(writeableFolderStringCache);
File oldConfigFilePath = new File(pathToUse + "/" + XmlFileInterface.settingsFileName); File oldConfigFilePath = new File(pathToUse + "/" + XmlFileInterface.settingsFileName);
if (oldConfigFilePath.exists() && oldConfigFilePath.canWrite()) if (oldConfigFilePath.exists() && oldConfigFilePath.canWrite())
{ {
Miscellaneous.logEvent("i", "Path", "Found old path " + pathToUse + " for settings and logs. Migrating old files to new directory.", 2); Miscellaneous.logEvent("i", "Path", "Found old path " + pathToUse + " for settings and logs. Migrating old files to new directory.", 2);
for (File fileToBeMoved : oldDirectory.listFiles()) for (File fileToBeMoved : oldDirectory.listFiles())
{ {
File dstFile = new File(writeableFolderStringCache + "/" + fileToBeMoved.getName()); File dstFile = new File(writeableFolderStringCache + "/" + fileToBeMoved.getName());
/* /*
For some stupid reason Android's file.moveTo can't move files between For some stupid reason Android's file.moveTo can't move files between
mount points. That's why we have to copy it and delete the src if successful. mount points. That's why we have to copy it and delete the src if successful.
*/ */
if(copyFileUsingStream(fileToBeMoved, dstFile)) if(copyFileUsingStream(fileToBeMoved, dstFile))
fileToBeMoved.delete(); fileToBeMoved.delete();
}
String message = String.format(Miscellaneous.getAnyContext().getResources().getString(R.string.filesHaveBeenMovedTo), newDirectory.getAbsolutePath());
Miscellaneous.writeStringToFile(oldDirectory.getAbsolutePath() + "/readme.txt", message);
break migration;
} }
String message = String.format(Miscellaneous.getAnyContext().getResources().getString(R.string.filesHaveBeenMovedTo), newDirectory.getAbsolutePath());
Miscellaneous.writeStringToFile(oldDirectory.getAbsolutePath() + "/readme.txt", message);
break migration;
}
// } // }
} }
} catch (Exception e) } catch (Exception e)
@@ -575,17 +575,17 @@ public class Miscellaneous extends Service
public static boolean isAndroidEmulator() public static boolean isAndroidEmulator()
{ {
String TAG = "EmulatorTest"; String TAG = "EmulatorTest";
String model = Build.MODEL; String model = Build.MODEL;
// Miscellaneous.logEvent("i", TAG, "model=" + model); // Miscellaneous.logEvent("i", TAG, "model=" + model);
String product = Build.PRODUCT; String product = Build.PRODUCT;
// Miscellaneous.logEvent("i", TAG, "product=" + product); // Miscellaneous.logEvent("i", TAG, "product=" + product);
boolean isEmulator = false; boolean isEmulator = false;
if (product != null) if (product != null)
{ {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_"); isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
} }
// Miscellaneous.logEvent("i", TAG, "isEmulator=" + isEmulator); // Miscellaneous.logEvent("i", TAG, "isEmulator=" + isEmulator);
return isEmulator; return isEmulator;
} }
public static boolean compare(String direction, String needle, String haystack) public static boolean compare(String direction, String needle, String haystack)
@@ -593,8 +593,8 @@ public class Miscellaneous extends Service
// If only one of needle or haystack is null // If only one of needle or haystack is null
if( if(
(needle == null && haystack != null) (needle == null && haystack != null)
|| ||
(needle != null && haystack == null) (needle != null && haystack == null)
) )
return false; return false;
@@ -703,8 +703,8 @@ public class Miscellaneous extends Service
public static String convertStreamToString(InputStream is) public static String convertStreamToString(InputStream is)
{ {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : ""; return s.hasNext() ? s.next() : "";
} }
public static Context getAnyContext() public static Context getAnyContext()
@@ -786,16 +786,16 @@ public class Miscellaneous extends Service
if( if(
source.contains("[d]") || source.contains("[d]") ||
source.contains("[m]") || source.contains("[m]") ||
source.contains("[Y]") || source.contains("[Y]") ||
source.contains("[h]") || source.contains("[h]") ||
source.contains("[H]") || source.contains("[H]") ||
source.contains("[i]") || source.contains("[i]") ||
source.contains("[s]") || source.contains("[s]") ||
source.contains("[ms]") || source.contains("[ms]") ||
source.contains("[w]") || source.contains("[w]") ||
source.contains("[F]") source.contains("[F]")
) )
{ {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
@@ -911,7 +911,7 @@ public class Miscellaneous extends Service
if (notificationText != null && notificationText.length() > 0) if (notificationText != null && notificationText.length() > 0)
//source = source.replace("[notificationText]", escapeStringForUrl(notificationText)); //source = source.replace("[notificationText]", escapeStringForUrl(notificationText));
source = source.replace("[notificationText]", notificationText); source = source.replace("[notificationText]", notificationText);
else else
{ {
source = source.replace("[notificationText]", "notificationText unknown"); source = source.replace("[notificationText]", "notificationText unknown");
@@ -1073,10 +1073,10 @@ public class Miscellaneous extends Service
} }
/** /**
* Checks if the device is rooted. * Checks if the device is rooted.
* *
* @return <code>true</code> if the device is rooted, <code>false</code> otherwise. * @return <code>true</code> if the device is rooted, <code>false</code> otherwise.
*/ */
public static boolean isPhoneRooted() public static boolean isPhoneRooted()
{ {
try try
@@ -1103,14 +1103,14 @@ public class Miscellaneous extends Service
} }
catch (Exception e1) catch (Exception e1)
{ {
// ignore // ignore
} }
// try executing commands // try executing commands
return canExecuteCommand("/system/xbin/which su") return canExecuteCommand("/system/xbin/which su")
|| ||
canExecuteCommand("/system/bin/which su") canExecuteCommand("/system/bin/which su")
|| ||
canExecuteCommand("which su"); canExecuteCommand("which su");
} }
} }
@@ -1130,7 +1130,7 @@ public class Miscellaneous extends Service
} }
return executedSuccesfully; return executedSuccesfully;
} }
public static char getDecimalSeparator() public static char getDecimalSeparator()
{ {
@@ -1179,10 +1179,10 @@ public class Miscellaneous extends Service
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
} }
/** /**
* Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
* aid testing on a local box, not for use on production. * aid testing on a local box, not for use on production.
*/ */
private static void disableSSLCertificateChecking() private static void disableSSLCertificateChecking()
{ {
try try
@@ -1227,47 +1227,47 @@ public class Miscellaneous extends Service
} }
} }
public static TrustManager[] getInsecureTrustManager() public static TrustManager[] getInsecureTrustManager()
{ {
TrustManager[] trustAllCerts = TrustManager[] trustAllCerts =
new TrustManager[] new TrustManager[]
{ {
new X509TrustManager() new X509TrustManager()
{ {
public X509Certificate[] getAcceptedIssuers() public X509Certificate[] getAcceptedIssuers()
{ {
return null; return null;
} }
@Override @Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{ {
// Not implemented // Not implemented
} }
@Override @Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{ {
// Not implemented // Not implemented
} }
} }
}; };
return trustAllCerts; return trustAllCerts;
} }
public static HostnameVerifier getInsecureHostnameVerifier() public static HostnameVerifier getInsecureHostnameVerifier()
{ {
HostnameVerifier allHostsValid = new HostnameVerifier() HostnameVerifier allHostsValid = new HostnameVerifier()
{ {
public boolean verify(String hostname, SSLSession session) public boolean verify(String hostname, SSLSession session)
{ {
return true; return true;
} }
}; };
return allHostsValid; return allHostsValid;
} }
@SuppressLint("NewApi") @SuppressLint("NewApi")
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@@ -2083,7 +2083,7 @@ public class Miscellaneous extends Service
//create dir if required while unzipping //create dir if required while unzipping
if (ze.isDirectory()) if (ze.isDirectory())
{ {
// dirChecker(ze.getName()); // dirChecker(ze.getName());
} }
else else
{ {
@@ -2175,49 +2175,49 @@ public class Miscellaneous extends Service
return formattedDate; return formattedDate;
} }
public static int arraySearchIndexOf(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine) public static int arraySearchIndexOf(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine)
{ {
if(matchFullLine) if(matchFullLine)
{ {
if(caseSensitive) if(caseSensitive)
{ {
for (int i = 0; i < haystack.length; i++) for (int i = 0; i < haystack.length; i++)
{ {
if (haystack[i].equals(needle)) if (haystack[i].equals(needle))
return i; return i;
} }
} }
else else
{ {
for (int i = 0; i < haystack.length; i++) for (int i = 0; i < haystack.length; i++)
{ {
if (haystack[i].toLowerCase().equals(needle.toLowerCase())) if (haystack[i].toLowerCase().equals(needle.toLowerCase()))
return i; return i;
} }
} }
} }
else else
{ {
if(caseSensitive) if(caseSensitive)
{ {
for (int i = 0; i < haystack.length; i++) for (int i = 0; i < haystack.length; i++)
{ {
if (haystack[i].contains(needle)) if (haystack[i].contains(needle))
return i; return i;
} }
} }
else else
{ {
for (int i = 0; i < haystack.length; i++) for (int i = 0; i < haystack.length; i++)
{ {
if (haystack[i].toLowerCase().contains(needle.toLowerCase())) if (haystack[i].toLowerCase().contains(needle.toLowerCase()))
return i; return i;
} }
} }
} }
return -1; return -1;
} }
public static boolean arraySearch(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine) public static boolean arraySearch(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine)
{ {