Search in sources :

Example 51 with Response

use of com.squareup.okhttp.Response in project stetho by facebook.

the class StethoInterceptorTest method testWithResponseCompression.

@Test
public void testWithResponseCompression() throws IOException {
    ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);
    byte[] uncompressedData = repeat(".", 1024).getBytes();
    byte[] compressedData = compress(uncompressedData);
    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setBody(new Buffer().write(compressedData)).addHeader("Content-Encoding: gzip"));
    Request request = new Request.Builder().url(server.url("/")).build();
    Response response = mClientWithInterceptor.newCall(request).execute();
    // Verify that the final output and the caller both saw the uncompressed stream.
    assertArrayEquals(uncompressedData, response.body().bytes());
    assertArrayEquals(uncompressedData, capturedOutput.toByteArray());
    // And verify that the StethoInterceptor was able to see both.
    Mockito.verify(mMockEventReporter).dataReceived(anyString(), eq(compressedData.length), eq(uncompressedData.length));
    server.shutdown();
}
Also used : Buffer(okio.Buffer) Response(com.squareup.okhttp.Response) MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) MockWebServer(com.squareup.okhttp.mockwebserver.MockWebServer) Request(com.squareup.okhttp.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 52 with Response

use of com.squareup.okhttp.Response in project stetho by facebook.

the class StethoInterceptorTest method testWithRequestCompression.

@Test
public void testWithRequestCompression() throws IOException {
    AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest = hookAlmostRealRequestWillBeSent(mMockEventReporter);
    MockWebServer server = new MockWebServer();
    server.start();
    server.enqueue(new MockResponse().setBody("Success!"));
    final byte[] decompressed = "Request text".getBytes();
    final byte[] compressed = compress(decompressed);
    assertNotEquals("Bogus test: decompressed and compressed lengths match", compressed.length, decompressed.length);
    RequestBody compressedBody = RequestBody.create(MediaType.parse("text/plain"), compress(decompressed));
    Request request = new Request.Builder().url(server.getUrl("/")).addHeader("Content-Encoding", "gzip").post(compressedBody).build();
    Response response = mClientWithInterceptor.newCall(request).execute();
    // Force a read to complete the flow.
    response.body().string();
    assertArrayEquals(decompressed, capturedRequest.get().body());
    Mockito.verify(mMockEventReporter).dataSent(anyString(), eq(decompressed.length), eq(compressed.length));
    server.shutdown();
}
Also used : Response(com.squareup.okhttp.Response) MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) MockResponse(com.squareup.okhttp.mockwebserver.MockResponse) MockWebServer(com.squareup.okhttp.mockwebserver.MockWebServer) Request(com.squareup.okhttp.Request) RequestBody(com.squareup.okhttp.RequestBody) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 53 with Response

use of com.squareup.okhttp.Response in project storymaker by StoryMaker.

the class StorymakerDownloadManager method downloadWithTor.

private void downloadWithTor(boolean useTor, Uri uri, String title, String desc, File targetFile) {
    initNotificationManager();
    // generate id/tag for notification
    String nTag = indexItem.getExpansionId();
    int nId = 0;
    if (fileName.contains(scal.io.liger.Constants.MAIN)) {
        nId = Integer.parseInt(indexItem.getExpansionFileVersion());
    } else if (fileName.contains(scal.io.liger.Constants.PATCH)) {
        nId = Integer.parseInt(indexItem.getPatchFileVersion());
    }
    // incompatible with lungcast certificate
    // StrongHttpsClient httpClient = getHttpClientInstance();
    OkHttpClient httpClient = new OkHttpClient();
    // we're now using this method to support non-tor downloads as well, so settings must be checked
    if (useTor) {
        if (checkTor(context)) {
            Timber.d("DOWNLOAD WITH TOR PROXY: " + scal.io.liger.Constants.TOR_PROXY_HOST + "/" + scal.io.liger.Constants.TOR_PROXY_PORT);
            SocketAddress torSocket = new InetSocketAddress(scal.io.liger.Constants.TOR_PROXY_HOST, scal.io.liger.Constants.TOR_PROXY_PORT);
            Proxy torProxy = new Proxy(Proxy.Type.HTTP, torSocket);
            httpClient.setProxy(torProxy);
        } else {
            Timber.e("CANNOT DOWNLOAD WITH TOR, TOR IS NOT ACTIVE");
            if (context instanceof Activity) {
                // FIXME move to strings
                Utils.toastOnUiThread((Activity) context, "Check settings, can't use tor if orbot isn't running", true);
            }
            StorymakerQueueManager.checkQueueFinished(context, targetFile.getName());
            return;
        }
    }
    // disable attempts to retry (more retries ties up connection and prevents failure handling)
    httpClient.setRetryOnConnectionFailure(false);
    // set modest timeout (longer timeout ties up connection and prevents failure handling)
    httpClient.setConnectTimeout(3000, TimeUnit.MILLISECONDS);
    String actualFileName = targetFile.getName().substring(0, targetFile.getName().lastIndexOf("."));
    Timber.d("CHECKING URI: " + uri.toString());
    try {
        // FIXME - adding the "Connection: close" header to resolve an issue that seemed to be caused
        // FIXME - by a lingering connection.  when possible, the better solution would be to track
        // FIXME - down the possible end states and add appropriate cleanup steps.
        Request request = new Request.Builder().url(uri.toString()).addHeader("Connection", "close").build();
        // check for partially downloaded file
        File partFile = new File(targetFile.getPath().replace(".tmp", ".part"));
        if (partFile.exists()) {
            long partBytes = partFile.length();
            Timber.d("PARTIAL FILE " + partFile.getPath() + " FOUND, SETTING RANGE HEADER: " + "Range" + " / " + "bytes=" + Long.toString(partBytes) + "-");
            // request.setHeader("Range", "bytes=" + Long.toString(partBytes) + "-");
            request = new Request.Builder().url(uri.toString()).addHeader("Connection", "close").addHeader("Range", "bytes=" + Long.toString(partBytes) + "-").build();
        } else {
            Timber.d("PARTIAL FILE " + partFile.getPath() + " NOT FOUND, STARTING AT BYTE 0");
        }
        Response response = httpClient.newCall(request).execute();
        int statusCode = response.code();
        if ((statusCode == 200) || (statusCode == 206)) {
            Timber.d("DOWNLOAD SUCCEEDED, STATUS CODE: " + statusCode);
            // queue item here, "download" doesn't start until after we get a status code
            // queue item, use date to get a unique long, subtract to get a negative number (to distinguish from download manager items)
            Date startTime = new Date();
            long queueId = 0 - startTime.getTime();
            StorymakerQueueManager.addToQueue(context, queueId, targetFile.getName(), queueDao);
            targetFile.getParentFile().mkdirs();
            Timber.d("DOWNLOAD SUCCEEDED, GETTING ENTITY...");
            BufferedInputStream responseInput = new BufferedInputStream(response.body().byteStream());
            try {
                FileOutputStream targetOutput = new FileOutputStream(targetFile);
                byte[] buf = new byte[1024];
                int i;
                int oldPercent = 0;
                long thisTime;
                long lastTime = -1;
                int lastPercent = 0;
                while ((i = responseInput.read(buf)) > 0) {
                    // create status bar notification
                    int nPercent = StorymakerDownloadHelper.getDownloadPercent(context, fileName, installedDao);
                    thisTime = System.currentTimeMillis();
                    if (oldPercent == nPercent) {
                    // need to cut back on notification traffic
                    } else {
                        if (nPercent % 10 == 0 && nPercent != lastPercent) {
                            if (lastTime == -1 || (thisTime - lastTime) > 1000) {
                                lastPercent = nPercent;
                                oldPercent = nPercent;
                                lastTime = thisTime;
                                Notification nProgress = new Notification.Builder(context).setContentTitle(mAppTitle + " content download").setContentText(// assignment file names are meaningless uuids
                                indexItem.getTitle() + " - " + (nPercent / 10.0) + "%").setSmallIcon(android.R.drawable.arrow_down_float).setProgress(100, (nPercent / 10), false).setWhen(startTime.getTime()).build();
                                nManager.notify(nTag, nId, nProgress);
                            // Log.d("Storymaker Download Manager", "** NOTIFICATION ** " + nPercent );
                            }
                        }
                    }
                    targetOutput.write(buf, 0, i);
                }
                targetOutput.close();
                responseInput.close();
                Timber.d("SAVED DOWNLOAD TO " + targetFile);
            } catch (ConnectTimeoutException cte) {
                Timber.e(cte, "FAILED TO SAVE DOWNLOAD TO " + actualFileName + " (CONNECTION EXCEPTION)");
            } catch (SocketTimeoutException ste) {
                Timber.e(ste, "FAILED TO SAVE DOWNLOAD TO " + actualFileName + " (SOCKET EXCEPTION)");
            } catch (IOException ioe) {
                Timber.e(ioe, "FAILED TO SAVE DOWNLOAD TO " + actualFileName + " (IO EXCEPTION)");
            }
            // remove from queue here, regardless of success
            StorymakerQueueManager.removeFromQueue(context, queueId, queueDao);
            // remove notification, regardless of success
            nManager.cancel(nTag, nId);
            // (assumes .tmp file will exist if download is interrupted)
            if (!handleFile(targetFile)) {
                Timber.e("ERROR DURING FILE PROCESSING FOR " + actualFileName);
            }
        } else {
            Timber.e("DOWNLOAD FAILED FOR " + actualFileName + ", STATUS CODE: " + statusCode);
            StorymakerQueueManager.checkQueueFinished(context, targetFile.getName());
        }
    // clean up connection
    // EntityUtils.consume(entity);
    // request.abort();
    // request.releaseConnection();
    } catch (IOException ioe) {
        Timber.e(ioe, "DOWNLOAD FAILED FOR " + actualFileName + ", EXCEPTION THROWN");
        StorymakerQueueManager.checkQueueFinished(context, targetFile.getName());
    }
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) InetSocketAddress(java.net.InetSocketAddress) Request(com.squareup.okhttp.Request) Activity(android.app.Activity) IOException(java.io.IOException) Date(java.util.Date) Notification(android.app.Notification) Response(com.squareup.okhttp.Response) HttpResponse(ch.boye.httpclientandroidlib.HttpResponse) Proxy(java.net.Proxy) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) File(java.io.File) ConnectTimeoutException(ch.boye.httpclientandroidlib.conn.ConnectTimeoutException)

Example 54 with Response

use of com.squareup.okhttp.Response in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class RequestTask method doInBackground.

@Override
protected String doInBackground(String... commandString) {
    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch(mType) {
        // OCID upload request from "APPLICATION" drawer title
        case DBE_UPLOAD_REQUEST:
            try {
                @Cleanup Realm realm = Realm.getDefaultInstance();
                boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);
                log.info("OCID upload data prepared - " + String.valueOf(prepared));
                if (prepared) {
                    File file = new File((mAppContext.getExternalFilesDir(null) + File.separator) + "OpenCellID/aimsicd-ocid-data.csv");
                    publishProgress(25, 100);
                    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile", "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file)).build();
                    Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv").post(requestBody).build();
                    publishProgress(60, 100);
                    Response response = okHttpClient.newCall(request).execute();
                    publishProgress(80, 100);
                    if (response != null) {
                        log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                        if (response.code() == 200) {
                            Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                            realm.executeTransaction(transaction);
                        }
                        publishProgress(95, 100);
                    }
                    return "Successful";
                } else {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                    return null;
                }
            // all caused by httpclient.execute(httppost);
            } catch (UnsupportedEncodingException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (FileNotFoundException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (IOException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (Exception e) {
                log.error("Upload OpenCellID data Exception", e);
            }
        // DOWNLOADING...
        case // OCID download request from "APPLICATION" drawer title
        DBE_DOWNLOAD_REQUEST:
            mTimeOut = REQUEST_TIMEOUT_MENU;
        case // OCID download request from "Antenna Map Viewer"
        DBE_DOWNLOAD_REQUEST_FROM_MAP:
            int count;
            try {
                long total;
                int progress = 0;
                String dirName = getOCDBDownloadDirectoryPath(mAppContext);
                File dir = new File(dirName);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, OCDB_File_Name);
                log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);
                Request request = new Request.Builder().url(commandString[0]).get().build();
                Response response;
                try {
                    // OCID's API can be slow. Give it up to a minute to do its job. Since this
                    // is a backgrounded task, it's ok to wait for a while.
                    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                    response = okHttpClient.newCall(request).execute();
                    // Restore back to default
                    okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
                } catch (SocketTimeoutException e) {
                    log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                    return "Timeout";
                }
                if (response.code() != 200) {
                    try {
                        String error = response.body().string();
                        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                        log.error("Download OCID data error: " + error);
                    } catch (Exception e) {
                        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + e.getClass().getName() + " - " + e.getMessage());
                        log.error("Download OCID exception: ", e);
                    }
                    return "Error";
                } else {
                    // This returns "-1" for streamed response (Chunked Transfer Encoding)
                    total = response.body().contentLength();
                    if (total == -1) {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                        // Let's set it arbitrarily to something other than "-1"
                        total = 1024;
                    } else {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                        // Let's show something!
                        publishProgress((int) (0.25 * total), (int) total);
                    }
                    FileOutputStream output = new FileOutputStream(file, false);
                    InputStream input = new BufferedInputStream(response.body().byteStream());
                    byte[] data = new byte[1024];
                    while ((count = input.read(data)) > 0) {
                        // writing data to file
                        output.write(data, 0, count);
                        progress += count;
                        publishProgress(progress, (int) total);
                    }
                    input.close();
                    // flushing output
                    output.flush();
                    output.close();
                }
                return "Successful";
            } catch (IOException e) {
                log.warn("Problem reading data from steam", e);
                return null;
            }
    }
    return null;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) Request(com.squareup.okhttp.Request) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Cleanup(lombok.Cleanup) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.squareup.okhttp.Response) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) MultipartBuilder(com.squareup.okhttp.MultipartBuilder) Realm(io.realm.Realm) File(java.io.File) RequestBody(com.squareup.okhttp.RequestBody)

Example 55 with Response

use of com.squareup.okhttp.Response in project Android-IMSI-Catcher-Detector by CellularPrivacy.

the class DeviceFragment method getOpenCellIdResponseCallback.

@NonNull
private Callback getOpenCellIdResponseCallback() {
    return new Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
            Handler refresh = new Handler(Looper.getMainLooper());
            refresh.post(new Runnable() {

                public void run() {
                    refreshFailed();
                }
            });
        }

        @Override
        public void onResponse(final Response response) throws IOException {
            Handler refresh = new Handler(Looper.getMainLooper());
            refresh.post(new Runnable() {

                public void run() {
                    Cell cell = responseToCell(response);
                    processFinish(cell);
                }
            });
        }
    };
}
Also used : Response(com.squareup.okhttp.Response) Callback(com.squareup.okhttp.Callback) Request(com.squareup.okhttp.Request) Handler(android.os.Handler) IOException(java.io.IOException) Cell(com.secupwn.aimsicd.utils.Cell) NonNull(android.support.annotation.NonNull)

Aggregations

Response (com.squareup.okhttp.Response)109 Request (com.squareup.okhttp.Request)75 IOException (java.io.IOException)70 OkHttpClient (com.squareup.okhttp.OkHttpClient)31 RequestBody (com.squareup.okhttp.RequestBody)23 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 ShowException (org.eyeseetea.malariacare.views.ShowException)7 Buffer (okio.Buffer)6 MediaType (com.squareup.okhttp.MediaType)5 InputStream (java.io.InputStream)5 HashMap (java.util.HashMap)5 Call (com.squareup.okhttp.Call)4 ApiException (io.kubernetes.client.ApiException)4