use of com.squareup.okhttp.Request 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.Request 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();
}
}
use of com.squareup.okhttp.Request in project xDrip-plus by jamorham.
the class GzipRequestInterceptor method sendFeedback.
public void sendFeedback(View myview) {
final EditText contact = (EditText) findViewById(R.id.contactText);
final EditText yourtext = (EditText) findViewById(R.id.yourText);
final OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(10, TimeUnit.SECONDS);
client.setReadTimeout(30, TimeUnit.SECONDS);
client.setWriteTimeout(30, TimeUnit.SECONDS);
client.interceptors().add(new GzipRequestInterceptor());
if (yourtext.length() == 0) {
toast("No text entered - cannot send blank");
return;
}
if (contact.length() == 0) {
toast("Without some contact info we cannot reply");
askEmailAddress();
return;
}
if (type_of_message.equals("Unknown")) {
askType();
return;
}
PersistentStore.setString(FEEDBACK_CONTACT_REFERENCE, contact.getText().toString());
toast("Sending..");
try {
final RequestBody formBody = new FormEncodingBuilder().add("contact", contact.getText().toString()).add("body", JoH.getDeviceDetails() + "\n" + JoH.getVersionDetails() + "\n" + getBestCollectorHardwareName() + "\n===\n\n" + yourtext.getText().toString() + " \n\n===\nType: " + type_of_message + "\nLog data:\n\n" + log_data + "\n\n\nSent: " + JoH.dateTimeText(JoH.tsl())).add("rating", String.valueOf(myrating.getRating())).add("type", type_of_message).build();
new Thread(new Runnable() {
public void run() {
try {
final Request request = new Request.Builder().url(send_url).post(formBody).build();
Log.i(TAG, "Sending feedback request");
final Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
JoH.static_toast_long(response.body().string());
log_data = "";
// Home.toaststatic("Feedback sent successfully");
finish();
} else {
JoH.static_toast_short("Error sending feedback: " + response.message().toString());
}
} catch (Exception e) {
Log.e(TAG, "Got exception in execute: " + e.toString());
JoH.static_toast_short("Error with network connection");
}
}
}).start();
} catch (Exception e) {
JoH.static_toast_short(e.getMessage());
Log.e(TAG, "General exception: " + e.toString());
}
}
use of com.squareup.okhttp.Request in project xDrip-plus by jamorham.
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 ariADDna by StnetixDevTeam.
the class ApiClient method buildCall.
/**
* Build HTTP call with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param progressRequestListener Progress request listener
* @return The HTTP call
* @throws ApiException If fail to serialize the request body object
*/
public Call buildCall(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(headerParams, reqBuilder);
String contentType = (String) headerParams.get("Content-Type");
// ensuring a default content type
if (contentType == null) {
contentType = "application/json";
}
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = serialize(body, contentType);
}
Request request = null;
if (progressRequestListener != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
request = reqBuilder.method(method, progressRequestBody).build();
} else {
request = reqBuilder.method(method, reqBody).build();
}
return httpClient.newCall(request);
}
Aggregations