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
{
protected static String writeableFolderStringCache = null;
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 http_error_string = "HTTP_ERROR";
protected final static String last_trigger_url_result_string = "last_trigger_url_result";
protected final static String httpMainData = "httpMainData";
protected final static String doNoEncodingString = "NoEncoding";
protected final static String httpEncoding = "UTF-8";
@@ -163,15 +163,15 @@ public class Miscellaneous extends Service
HttpClient httpclient = new DefaultHttpClient();
StringBuilder responseBody = new StringBuilder();
boolean errorFound = false;
try
{
try
{
URL urlObject = new URL(url);
HttpURLConnection connection;
if(url.toLowerCase().contains("https"))
try
{
try
{
URL urlObject = new URL(url);
HttpURLConnection connection;
if(url.toLowerCase().contains("https"))
{
connection = (HttpsURLConnection) urlObject.openConnection();
if(Settings.httpAcceptAllCertificates)
@@ -187,21 +187,21 @@ public class Miscellaneous extends Service
}
}
else
connection = (HttpURLConnection) urlObject.openConnection();
else
connection = (HttpURLConnection) urlObject.openConnection();
// Add http simple authentication if specified
if(username != null && password != null)
{
String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encodedCredentials);
}
// Add http simple authentication if specified
if(username != null && password != null)
{
String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encodedCredentials);
}
else if(method.equals(ActivityManageActionTriggerUrl.methodPost))
connection.setRequestMethod("POST");
if(httpParams.size() > 0)
if(httpParams != null && httpParams.size() > 0)
{
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
@@ -220,29 +220,29 @@ public class Miscellaneous extends Service
writer.close();
}
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null)
responseBody.append(line + Miscellaneous.lineSeparator);
}
catch(Exception e)
{
Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3);
errorFound = true;
}
}
finally
{
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
if(errorFound)
return http_error_string;
else
return responseBody.toString();
}
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null)
responseBody.append(line + Miscellaneous.lineSeparator);
}
catch(Exception e)
{
Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3);
errorFound = true;
}
}
finally
{
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
if(errorFound)
return http_error_string;
else
return responseBody.toString();
}
}
private static String getQuery(List<NameValuePair> params, String method) throws UnsupportedEncodingException
@@ -295,35 +295,35 @@ public class Miscellaneous extends Service
return result.toString();
}
public static String downloadUrlWithoutCertificateChecking(String url, String username, String password, String method, Map<String, String> httpParams)
{
try
{
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
{
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);
httpclient = Actions.getInsecureSslClient(httpclient);
HttpRequestBase httpRequest;
if(
method.equals(ActivityManageActionTriggerUrl.methodPost)
||
(username != null && password != null)
(username != null && password != null)
||
httpParams.size() > 0
)
httpParams.size() > 0
)
httpRequest = new HttpPost(url);
else
httpRequest = new HttpGet(url);
// Add http simple authentication if specified
if(username != null && password != null)
{
String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT);
// Add http simple authentication if specified
if(username != null && password != null)
{
String encodedCredentials = Base64.encodeToString(new String(username + ":" + password).getBytes(), Base64.DEFAULT);
httpRequest.addHeader("Authorization", "Basic " + encodedCredentials);
}
}
if(httpParams.size() > 0)
{
@@ -334,20 +334,20 @@ public class Miscellaneous extends Service
((HttpPost)httpRequest).setEntity(new UrlEncodedFormEntity(paramPairs, "UTF-8"));
}
HttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
if (entity != null)
{
HttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
if (entity != null)
{
// System.out.println(EntityUtils.toString(entity));
return EntityUtils.toString(entity);
}
}
catch(Exception e)
{
return EntityUtils.toString(entity);
}
}
catch(Exception e)
{
Miscellaneous.logEvent("e", "HTTP error", Log.getStackTraceString(e), 3);
return http_error_string;
}
}
// finally
// {
// // When HttpClient instance is no longer needed,
@@ -356,34 +356,34 @@ public class Miscellaneous extends Service
// httpclient.getConnectionManager().shutdown();
// return responseBody.toString();
// }
return null;
return null;
}
public static int boolToInt(boolean input)
{
if(input)
return 1;
else
return 0;
}
public static int boolToInt(boolean input)
{
if(input)
return 1;
else
return 0;
}
@Override
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
public static void logEvent(String type, String header, String description, int logLevel)
{
try
{
header = getAnyContext().getResources().getString(R.string.app_name);
}
catch(NullPointerException e)
{
header = "Automation";
}
try
{
header = getAnyContext().getResources().getString(R.string.app_name);
}
catch(NullPointerException e)
{
header = "Automation";
}
if(Settings.logToConsole)
{
@@ -411,19 +411,19 @@ public class Miscellaneous extends Service
protected static boolean logCleanerRunning = false;
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))
{
Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file.", 3);
File archivedLogFile = new File(getWriteableFolder() + "/" + logFileName + "-old");
logFile.renameTo(archivedLogFile);
Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file finished. Old log renamed to " + archivedLogFile.getAbsolutePath(), 3);
}
if(logFile.exists() && logFile.length() > (maxSizeInBytes))
{
Miscellaneous.logEvent("i", "Logfile", "Cleaning up log file.", 3);
File archivedLogFile = new File(getWriteableFolder() + "/" + logFileName + "-old");
logFile.renameTo(archivedLogFile);
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)
@@ -492,34 +492,34 @@ public class Miscellaneous extends Service
{
// 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();
// Migrate existing files
File oldDirectory = new File(pathToUse);
File newDirectory = new File(writeableFolderStringCache);
File oldConfigFilePath = new File(pathToUse + "/" + XmlFileInterface.settingsFileName);
if (oldConfigFilePath.exists() && oldConfigFilePath.canWrite())
{
Miscellaneous.logEvent("i", "Path", "Found old path " + pathToUse + " for settings and logs. Migrating old files to new directory.", 2);
// Migrate existing files
File oldDirectory = new File(pathToUse);
File newDirectory = new File(writeableFolderStringCache);
File oldConfigFilePath = new File(pathToUse + "/" + XmlFileInterface.settingsFileName);
if (oldConfigFilePath.exists() && oldConfigFilePath.canWrite())
{
Miscellaneous.logEvent("i", "Path", "Found old path " + pathToUse + " for settings and logs. Migrating old files to new directory.", 2);
for (File fileToBeMoved : oldDirectory.listFiles())
{
File dstFile = new File(writeableFolderStringCache + "/" + fileToBeMoved.getName());
for (File fileToBeMoved : oldDirectory.listFiles())
{
File dstFile = new File(writeableFolderStringCache + "/" + fileToBeMoved.getName());
/*
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.
*/
if(copyFileUsingStream(fileToBeMoved, dstFile))
fileToBeMoved.delete();
}
String message = String.format(Miscellaneous.getAnyContext().getResources().getString(R.string.filesHaveBeenMovedTo), newDirectory.getAbsolutePath());
Miscellaneous.writeStringToFile(oldDirectory.getAbsolutePath() + "/readme.txt", message);
break migration;
if(copyFileUsingStream(fileToBeMoved, dstFile))
fileToBeMoved.delete();
}
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)
@@ -560,10 +560,10 @@ public class Miscellaneous extends Service
FileWriter fileWriter = new FileWriter(getLogFile(), true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Date date = new Date();
bufferedWriter.write("\n" + date + ": " + type + " / " + header + " / " + description);
bufferedWriter.close();
// Log.i("LogFile", "Log entry written.");
}
catch(Exception e)
@@ -571,21 +571,21 @@ public class Miscellaneous extends Service
Log.e("LogFile", "Error writing logs to file: " + e.getMessage());
}
}
public static boolean isAndroidEmulator()
{
String TAG = "EmulatorTest";
String model = Build.MODEL;
String model = Build.MODEL;
// Miscellaneous.logEvent("i", TAG, "model=" + model);
String product = Build.PRODUCT;
String product = Build.PRODUCT;
// Miscellaneous.logEvent("i", TAG, "product=" + product);
boolean isEmulator = false;
if (product != null)
{
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
boolean isEmulator = false;
if (product != null)
{
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
// Miscellaneous.logEvent("i", TAG, "isEmulator=" + isEmulator);
return isEmulator;
return isEmulator;
}
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(
(needle == null && haystack != null)
||
(needle != null && haystack == null)
||
(needle != null && haystack == null)
)
return false;
@@ -619,29 +619,29 @@ public class Miscellaneous extends Service
return false;
}
}
public static int compareTimes(TimeObject time1, TimeObject time2)
{
// Miscellaneous.logEvent("i", "TimeCompare", "To compare: " + time1.toString() + " / " + time2.toString());
if(time1.getHours() == time2.getHours() && time1.getMinutes() == time2.getMinutes())
{
// Miscellaneous.logEvent("i", "TimeCompare", "Times are equal.");
return 0;
}
if(time1.getHours() > time2.getHours())
{
// Miscellaneous.logEvent("i", "TimeCompare", "Time1 is bigger/later by hours.");
return -1;
}
if(time1.getHours() < time2.getHours())
{
// Miscellaneous.logEvent("i", "TimeCompare", "Time2 is bigger/later by hours.");
return 1;
}
if(time1.getHours() == time2.getHours())
{
if(time1.getMinutes() < time2.getMinutes())
@@ -649,14 +649,14 @@ public class Miscellaneous extends Service
// Miscellaneous.logEvent("i", "TimeCompare", "Hours are equal. Time2 is bigger/later by minutes.");
return 1;
}
if(time1.getMinutes() > time2.getMinutes())
{
// Miscellaneous.logEvent("i", "TimeCompare", "Hours are equal. Time1 is bigger/later by minutes.");
return -1;
}
}
Miscellaneous.logEvent("i", "TimeCompare", "Default return code. Shouldn't be here.", 5);
return 0;
@@ -700,13 +700,13 @@ public class Miscellaneous extends Service
Miscellaneous.logEvent("i", "TimeCompare", "Default return code. Shouldn't be here.", 5);
return 0;
}
public static String convertStreamToString(InputStream is)
{
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public static Context getAnyContext()
{
Context returnContext;
@@ -744,7 +744,7 @@ public class Miscellaneous extends Service
return false;
}
}
@SuppressLint("NewApi")
public static String replaceVariablesInText(String source, Context context) throws Exception
{
@@ -752,7 +752,7 @@ public class Miscellaneous extends Service
// Miscellaneous.logEvent("i", "Raw source", source);
if(source.contains("[uniqueid]"))
source = source.replace("[uniqueid]", Secure.getString(context.getContentResolver(), Secure.ANDROID_ID));
if(source.contains("[latitude]") | source.contains("[longitude]"))
{
if(LocationProvider.getLastKnownLocation() != null)
@@ -765,17 +765,17 @@ public class Miscellaneous extends Service
Miscellaneous.logEvent("w", "TriggerURL", context.getResources().getString(R.string.triggerUrlReplacementPositionError), 3);
}
}
if(source.contains("[phonenr]"))
{
String lastPhoneNr = PhoneStatusListener.getLastPhoneNumber();
if(lastPhoneNr != null && lastPhoneNr.length() > 0)
source = source.replace("[phonenr]", PhoneStatusListener.getLastPhoneNumber());
else
Miscellaneous.logEvent("w", "TriggerURL", context.getResources().getString(R.string.triggerUrlReplacementPositionError), 3);
}
if(source.contains("[serialnr]"))
{
if (Build.VERSION.SDK_INT > 8)
@@ -786,16 +786,16 @@ public class Miscellaneous extends Service
if(
source.contains("[d]") ||
source.contains("[m]") ||
source.contains("[Y]") ||
source.contains("[h]") ||
source.contains("[H]") ||
source.contains("[i]") ||
source.contains("[s]") ||
source.contains("[ms]") ||
source.contains("[w]") ||
source.contains("[F]")
)
source.contains("[m]") ||
source.contains("[Y]") ||
source.contains("[h]") ||
source.contains("[H]") ||
source.contains("[i]") ||
source.contains("[s]") ||
source.contains("[ms]") ||
source.contains("[w]") ||
source.contains("[F]")
)
{
Calendar cal = Calendar.getInstance();
@@ -911,7 +911,7 @@ public class Miscellaneous extends Service
if (notificationText != null && notificationText.length() > 0)
//source = source.replace("[notificationText]", escapeStringForUrl(notificationText));
source = source.replace("[notificationText]", notificationText);
source = source.replace("[notificationText]", notificationText);
else
{
source = source.replace("[notificationText]", "notificationText unknown");
@@ -1016,18 +1016,18 @@ public class Miscellaneous extends Service
source = source.substring(0, pos1) + escapeStringForUrl(replacement) + source.substring(pos2 +1);
}
// Miscellaneous.logEvent("i", "URL after replace", source);
return source;
}
/**
* Write a log entry and exit the application, so the crash is actually visible.
* Might even cause the activity to be automatically restarted by the OS.
*/
public static UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler()
{
{
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
@@ -1035,13 +1035,13 @@ public class Miscellaneous extends Service
System.exit(0);
}
};
public static AlertDialog messageBox(String title, String message, Context context)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setMessage(message);
alertDialog.setPositiveButton(context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener()
{
@@ -1071,12 +1071,12 @@ public class Miscellaneous extends Service
}
return haveConnectedWifi || haveConnectedMobile;
}
/**
* Checks if the device is rooted.
*
* @return <code>true</code> if the device is rooted, <code>false</code> otherwise.
*/
* Checks if the device is rooted.
*
* @return <code>true</code> if the device is rooted, <code>false</code> otherwise.
*/
public static boolean isPhoneRooted()
{
try
@@ -1103,14 +1103,14 @@ public class Miscellaneous extends Service
}
catch (Exception e1)
{
// ignore
// ignore
}
// try executing commands
return canExecuteCommand("/system/xbin/which su")
||
||
canExecuteCommand("/system/bin/which su")
||
||
canExecuteCommand("which su");
}
}
@@ -1130,7 +1130,7 @@ public class Miscellaneous extends Service
}
return executedSuccesfully;
}
}
public static char getDecimalSeparator()
{
@@ -1173,16 +1173,16 @@ public class Miscellaneous extends Service
else
return true;
}
public static boolean isNumeric(String str)
{
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
* aid testing on a local box, not for use on production.
*/
/**
* 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.
*/
private static void disableSSLCertificateChecking()
{
try
@@ -1226,48 +1226,48 @@ public class Miscellaneous extends Service
Miscellaneous.logEvent("e", "SSL", Log.getStackTraceString(e), 4);
}
}
public static TrustManager[] getInsecureTrustManager()
{
TrustManager[] trustAllCerts =
public static TrustManager[] getInsecureTrustManager()
{
TrustManager[] trustAllCerts =
new TrustManager[]
{
new X509TrustManager()
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
// Not implemented
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
// Not implemented
}
}
};
{
new X509TrustManager()
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
// Not implemented
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
// Not implemented
}
}
};
return trustAllCerts;
}
public static HostnameVerifier getInsecureHostnameVerifier()
{
HostnameVerifier allHostsValid = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
return allHostsValid;
}
}
public static HostnameVerifier getInsecureHostnameVerifier()
{
HostnameVerifier allHostsValid = new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
};
return allHostsValid;
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@@ -2083,7 +2083,7 @@ public class Miscellaneous extends Service
//create dir if required while unzipping
if (ze.isDirectory())
{
// dirChecker(ze.getName());
// dirChecker(ze.getName());
}
else
{
@@ -2175,49 +2175,49 @@ public class Miscellaneous extends Service
return formattedDate;
}
public static int arraySearchIndexOf(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine)
{
if(matchFullLine)
{
if(caseSensitive)
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].equals(needle))
return i;
}
}
else
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].toLowerCase().equals(needle.toLowerCase()))
return i;
}
}
}
else
{
if(caseSensitive)
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].contains(needle))
return i;
}
}
else
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].toLowerCase().contains(needle.toLowerCase()))
return i;
}
}
}
public static int arraySearchIndexOf(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine)
{
if(matchFullLine)
{
if(caseSensitive)
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].equals(needle))
return i;
}
}
else
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].toLowerCase().equals(needle.toLowerCase()))
return i;
}
}
}
else
{
if(caseSensitive)
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].contains(needle))
return i;
}
}
else
{
for (int i = 0; i < haystack.length; i++)
{
if (haystack[i].toLowerCase().contains(needle.toLowerCase()))
return i;
}
}
}
return -1;
}
return -1;
}
public static boolean arraySearch(String[] haystack, String needle, boolean caseSensitive, boolean matchFullLine)
{