use of com.squareup.okhttp.Request in project xDrip by NightscoutFoundation.
the class WixelReader method readHttpJson.
// read from http source like cloud hosted parakeet receiver.cgi / json.get
private static List<TransmitterRawData> readHttpJson(String url, int numberOfRecords) {
final List<TransmitterRawData> trd_list = new LinkedList<>();
int processNumberOfRecords = numberOfRecords;
// TODO make this work on preference option for the feature
if (true)
numberOfRecords = numberOfRecords + 1;
long newest_timestamp = 0;
try {
if (httpClient == null) {
httpClient = new OkHttpClient();
// suitable for GPRS
httpClient.setConnectTimeout(30, TimeUnit.SECONDS);
httpClient.setReadTimeout(60, TimeUnit.SECONDS);
httpClient.setWriteTimeout(20, TimeUnit.SECONDS);
}
// simple HTTP GET request
// n=numberOfRecords for backfilling
// r=sequence number to avoid any cache
// expecting json reply like the standard json server in dexterity / python pi usb / parakeet
final Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0").header("Connection", "close").url(url + "?n=" + Integer.toString(numberOfRecords) + "&r=" + Long.toString((System.currentTimeMillis() / 1000) % 9999999)).build();
final Response response = httpClient.newCall(request).execute();
// if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
if (response.isSuccessful()) {
String[] lines = response.body().string().split("\\r?\\n");
for (String data : lines) {
if (data == null) {
Log.d(TAG, "received null continuing");
continue;
}
if (data.equals("")) {
Log.d(TAG, "received \"\" continuing");
continue;
}
final TransmitterRawData trd = gson.fromJson(data, TransmitterRawData.class);
trd.CaptureDateTime = System.currentTimeMillis() - trd.RelativeTime;
// Versions of the Python USB script after 20th May 2016 will
// submit a bogus geolocation in the middle of the ocean to differentiate
// themselves from actual parakeet data even though both can coexist on the
// parakeet web service.
// if (JoH.ratelimit("parakeet-check-notification", 9)) {
ParakeetHelper.checkParakeetNotifications(trd.CaptureDateTime, trd.GeoLocation);
// }
if ((trd.GeoLocation != null)) {
if (!trd.GeoLocation.equals("-15,-15")) {
try {
MapsActivity.newMapLocation(trd.GeoLocation, trd.CaptureDateTime);
} catch (Exception e) {
Log.e(TAG, "Exception with maps activity: " + e.toString());
}
} else {
// look a little further if we see usb-wixel data on parakeet app engine
processNumberOfRecords = numberOfRecords + 1;
}
}
if (newest_timestamp < trd.getCaptureDateTime()) {
statusLog(url, JoH.hourMinuteString() + " OK data from:", trd.getCaptureDateTime());
newest_timestamp = trd.CaptureDateTime;
}
trd_list.add(0, trd);
// System.out.println( trd.toTableString());
if (trd_list.size() == processNumberOfRecords) {
// We have the data we want, let's get out
break;
}
}
Log.i(TAG, "Success getting http json with end size: " + Integer.toString(trd_list.size()));
}
} catch (Exception e) {
Log.e(TAG, "caught Exception in reading http json data " + e.toString());
}
return trd_list;
}
use of com.squareup.okhttp.Request in project xDrip by NightscoutFoundation.
the class GzipRequestInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder().header("Content-Encoding", "gzip").method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))).build();
return chain.proceed(compressedRequest);
}
use of com.squareup.okhttp.Request in project xDrip by NightscoutFoundation.
the class ShareRest method getOkHttpClient.
private synchronized OkHttpClient getOkHttpClient() {
try {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
try {
// Add user-agent and relevant headers.
Request original = chain.request();
Request copy = original.newBuilder().build();
Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
Log.d(TAG, "Sending request: " + modifiedRequest.toString());
Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
Log.d(TAG, "Request body: " + buffer.readUtf8());
final Response response = chain.proceed(modifiedRequest);
Log.d(TAG, "Received response: " + response.toString());
if (response.body() != null) {
MediaType contentType = response.body().contentType();
String bodyString = response.body().string();
Log.d(TAG, "Response body: " + bodyString);
return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
} else
return response;
} catch (NullPointerException e) {
Log.e(TAG, "Got null pointer exception: " + e);
return null;
} catch (IllegalStateException e) {
UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
return null;
}
}
});
okHttpClient.setSslSocketFactory(sslSocketFactory);
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException("Error occurred initializing OkHttp: ", e);
}
}
use of com.squareup.okhttp.Request in project xDrip by NightscoutFoundation.
the class WebAppHelper method doInBackground.
@Override
protected Integer doInBackground(String... url) {
try {
Log.d(TAG, "Processing URL: " + url[0]);
Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0 (jamorham)").header("Connection", "close").url(url[0]).build();
client.setConnectTimeout(15, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);
final Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
body = response.body().bytes();
} catch (Exception e) {
Log.d(TAG, "Exception in background task: " + e.toString());
}
return body.length;
}
use of com.squareup.okhttp.Request in project xDrip by NightscoutFoundation.
the class UpdateActivity method checkForAnUpdate.
public static void checkForAnUpdate(final Context context) {
if (prefs == null)
prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (!prefs.getBoolean(autoUpdatePrefsName, true))
return;
if (last_check_time == 0)
last_check_time = (double) prefs.getLong(last_update_check_time, 0);
if (((JoH.ts() - last_check_time) > 86300000) || (debug)) {
last_check_time = JoH.ts();
prefs.edit().putLong(last_update_check_time, (long) last_check_time).apply();
String channel = prefs.getString("update_channel", "beta");
Log.i(TAG, "Checking for a software update, channel: " + channel);
String subversion = "";
if (!context.getString(R.string.app_name).equals("xDrip+")) {
subversion = context.getString(R.string.app_name).replaceAll("[^a-zA-Z0-9]", "");
Log.d(TAG, "Using subversion: " + subversion);
}
final String CHECK_URL = context.getString(R.string.wserviceurl) + "/update-check/" + channel + subversion;
DOWNLOAD_URL = "";
newversion = 0;
new Thread(new Runnable() {
public void run() {
try {
if (httpClient == null) {
httpClient = new OkHttpClient();
httpClient.setConnectTimeout(30, TimeUnit.SECONDS);
httpClient.setReadTimeout(60, TimeUnit.SECONDS);
httpClient.setWriteTimeout(20, TimeUnit.SECONDS);
}
getVersionInformation(context);
if (versionnumber == 0)
return;
String locale = "";
try {
locale = Locale.getDefault().toString();
if (locale == null)
locale = "";
} catch (Exception e) {
// do nothing
}
final Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0").header("Connection", "close").url(CHECK_URL + "?r=" + Long.toString((System.currentTimeMillis() / 100000) % 9999999) + "&ln=" + JoH.urlEncode(locale)).build();
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
final String[] lines = response.body().string().split("\\r?\\n");
if (lines.length > 1) {
try {
newversion = Integer.parseInt(lines[0]);
if ((newversion > versionnumber) || (debug)) {
if (lines[1].startsWith("http")) {
Log.i(TAG, "Notifying user of new update available our version: " + versionnumber + " new: " + newversion);
DOWNLOAD_URL = lines[1];
if (lines.length > 2) {
try {
FILE_SIZE = Integer.parseInt(lines[2]);
} catch (NumberFormatException | NullPointerException e) {
Log.e(TAG, "Got exception processing update download parameters");
}
} else {
FILE_SIZE = -1;
}
if (lines.length > 3) {
MESSAGE = lines[3];
} else {
MESSAGE = "";
}
if (lines.length > 4) {
CHECKSUM = lines[4];
} else {
CHECKSUM = "";
}
final Intent intent = new Intent(context, UpdateActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
Log.e(TAG, "Error parsing second line of update reply");
}
} else {
Log.i(TAG, "Our current version is the most recent: " + versionnumber + " vs " + newversion);
}
} catch (Exception e) {
Log.e(TAG, "Got exception parsing update version: " + e.toString());
}
} else {
Log.d(TAG, "zero lines received in reply");
}
Log.i(TAG, "Success getting latest software version");
} else {
Log.d(TAG, "Failure getting update URL data: code: " + response.code());
}
} catch (Exception e) {
UserError.Log.e(TAG, "Exception in reading http update version " + e.toString());
}
// for GC
httpClient = null;
}
}).start();
}
}
Aggregations