Files
RidgeScout/app/src/main/java/com/ridgebotics/ridgescout/utility/RequestTask.java
T

79 lines
2.4 KiB
Java
Raw Normal View History

2024-09-15 22:47:45 -06:00
package com.ridgebotics.ridgescout.utility;
2024-03-28 10:21:54 -06:00
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.function.Function;
import javax.net.ssl.HttpsURLConnection;
2025-04-21 12:06:37 -06:00
// Class to send an http request
// Used for TBA
2024-03-28 10:21:54 -06:00
public class RequestTask extends AsyncTask<String, String, String> {
private Function<String, String> resultFunction = null;
@Override
protected String doInBackground(String... uri) {
try {
URL url = new URL(uri[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String[] headers = uri[1].split(", ");
for(String header : headers){
String[] split = header.split(": ");
conn.setRequestProperty(split[0], split[1]);
}
if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
// ByteArrayOutputStream out = new ByteArrayOutputStream();
return readStream(conn.getInputStream());
// Do normal input or output stream reading
}
else {
return null; // See documentation for more info on response handling
}
} catch (IOException e) {
2025-03-24 12:41:43 -06:00
AlertManager.error("Failed to download!", e);
2024-03-28 10:21:54 -06:00
}
return null;
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
2024-03-28 10:21:54 -06:00
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
2024-03-28 10:21:54 -06:00
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
AlertManager.error(e);
2024-03-28 10:21:54 -06:00
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
AlertManager.error(e);
2024-03-28 10:21:54 -06:00
}
}
}
return response.toString();
}
public void onResult(Function<String, String> func) {
this.resultFunction = func;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(resultFunction != null){
resultFunction.apply(result);
}
}
}