Search in sources :

Example 16 with Response

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);
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) MediaType(com.squareup.okhttp.MediaType) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(com.squareup.okhttp.Interceptor) Buffer(okio.Buffer) Request(com.squareup.okhttp.Request) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Response(com.squareup.okhttp.Response) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 17 with Response

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;
}
Also used : Response(com.squareup.okhttp.Response) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) IOException(java.io.IOException)

Example 18 with Response

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();
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) Intent(android.content.Intent) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Response(com.squareup.okhttp.Response)

Example 19 with Response

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");
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) FormEncodingBuilder(com.squareup.okhttp.FormEncodingBuilder) PowerManager(android.os.PowerManager) Response(com.squareup.okhttp.Response) RequestBody(com.squareup.okhttp.RequestBody)

Example 20 with Response

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();
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) Request(com.squareup.okhttp.Request) Intent(android.content.Intent) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Response(com.squareup.okhttp.Response)

Aggregations

Response (com.squareup.okhttp.Response)108 Request (com.squareup.okhttp.Request)75 IOException (java.io.IOException)72 OkHttpClient (com.squareup.okhttp.OkHttpClient)33 RequestBody (com.squareup.okhttp.RequestBody)24 JSONException (org.json.JSONException)16 JSONObject (org.json.JSONObject)15 FormEncodingBuilder (com.squareup.okhttp.FormEncodingBuilder)14 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10 ApiCallException (org.eyeseetea.malariacare.domain.exception.ApiCallException)10 Callback (com.squareup.okhttp.Callback)9 SocketTimeoutException (java.net.SocketTimeoutException)8 File (java.io.File)7 Buffer (okio.Buffer)7 ShowException (org.eyeseetea.malariacare.views.ShowException)7 MediaType (com.squareup.okhttp.MediaType)5 InputStream (java.io.InputStream)5 ResponseBody (com.squareup.okhttp.ResponseBody)4 ApiException (io.kubernetes.client.ApiException)4 FileOutputStream (java.io.FileOutputStream)4