use of com.squareup.okhttp.Response 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.Response 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.Response 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();
}
}
use of com.squareup.okhttp.Response in project xDrip-plus by jamorham.
the class DisplayQRCode method uploadBytes.
public static void uploadBytes(byte[] result, final int callback_option) {
final PowerManager.WakeLock wl = JoH.getWakeLock("uploadBytes", 1200000);
if ((result != null) && (result.length > 0)) {
final byte[] mykey = CipherUtils.getRandomKey();
byte[] crypted_data = CipherUtils.encryptBytes(JoH.compressBytesToBytes(result), mykey);
if ((crypted_data != null) && (crypted_data.length > 0)) {
Log.d(TAG, "Before: " + result.length + " After: " + crypted_data.length);
final OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);
toast("Preparing");
try {
send_url = xdrip.getAppContext().getString(R.string.wserviceurl) + "/joh-setsw";
final String bbody = Base64.encodeToString(crypted_data, Base64.NO_WRAP);
Log.d(TAG, "Upload Body size: " + bbody.length());
final RequestBody formBody = new FormEncodingBuilder().add("data", bbody).build();
new Thread(new Runnable() {
public void run() {
try {
final Request request = new Request.Builder().header("User-Agent", "Mozilla/5.0 (jamorham)").header("Connection", "close").url(send_url).post(formBody).build();
Log.i(TAG, "Uploading data");
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
final String reply = response.body().string();
Log.d(TAG, "Got success response length: " + reply.length() + " " + reply);
if ((reply.length() == 35) && (reply.startsWith("ID:"))) {
switch(callback_option) {
case 1:
{
if (mInstance != null) {
mInstance.display_final_all_settings_qr_code(reply.substring(3, 35), mykey);
} else {
Log.e(TAG, "mInstance null");
}
break;
}
case 2:
{
GcmActivity.backfillLink(reply.substring(3, 35), JoH.bytesToHex(mykey));
break;
}
default:
{
toast("Invalid callback option on upload");
}
}
} else {
Log.d(TAG, "Got unhandled reply: " + reply);
toast(reply);
}
} else {
toast("Error please try again");
}
} catch (Exception e) {
Log.e(TAG, "Got exception in execute: " + e.toString());
e.printStackTrace();
toast("Error with connection");
}
}
}).start();
} catch (Exception e) {
toast(e.getMessage());
Log.e(TAG, "General exception: " + e.toString());
} finally {
JoH.releaseWakeLock(wl);
}
} else {
toast("Something went wrong preparing the settings");
}
} else {
toast("Could not read data somewhere");
}
}
use of com.squareup.okhttp.Response in project xDrip-plus by jamorham.
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