Search in sources :

Example 31 with Request

use of com.tonyodev.fetch2.Request in project cw-omnibus by commonsguy.

the class LoadThread method run.

@Override
public void run() {
    try {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(SO_URL).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            Reader in = response.body().charStream();
            BufferedReader reader = new BufferedReader(in);
            SOQuestions questions = new Gson().fromJson(reader, SOQuestions.class);
            reader.close();
            EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
        } else {
            Log.e(getClass().getSimpleName(), response.toString());
        }
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedReader(java.io.BufferedReader) BufferedReader(java.io.BufferedReader) Reader(java.io.Reader) Gson(com.google.gson.Gson)

Example 32 with Request

use of com.tonyodev.fetch2.Request in project cw-omnibus by commonsguy.

the class Downloader method onHandleIntent.

@Override
public void onHandleIntent(Intent i) {
    mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    try {
        String filename = i.getData().getLastPathSegment();
        NotificationCompat.Builder builder = buildForeground(filename);
        final Notification notif = builder.build();
        startForeground(FOREGROUND_ID, notif);
        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        root.mkdirs();
        File output = new File(root, filename);
        if (output.exists()) {
            output.delete();
        }
        final ProgressResponseBody.Listener progressListener = new ProgressResponseBody.Listener() {

            long lastUpdateTime = 0L;

            @Override
            public void onProgressChange(long bytesRead, long contentLength, boolean done) {
                long now = SystemClock.uptimeMillis();
                if (now - lastUpdateTime > 1000) {
                    notif.contentView.setProgressBar(android.R.id.progress, (int) contentLength, (int) bytesRead, false);
                    mgr.notify(FOREGROUND_ID, notif);
                    lastUpdateTime = now;
                }
            }
        };
        Interceptor nightTrain = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response original = chain.proceed(chain.request());
                Response.Builder b = original.newBuilder().body(new ProgressResponseBody(original.body(), progressListener));
                return (b.build());
            }
        };
        OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(nightTrain).build();
        Request request = new Request.Builder().url(i.getData().toString()).build();
        Response response = client.newCall(request).execute();
        String contentType = response.header("Content-type");
        BufferedSink sink = Okio.buffer(Okio.sink(new File(output.getPath())));
        sink.writeAll(response.body().source());
        sink.close();
        stopForeground(true);
        raiseNotification(contentType, output, null);
    } catch (IOException e2) {
        stopForeground(true);
        raiseNotification(null, null, e2);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Notification(android.app.Notification) Response(okhttp3.Response) NotificationCompat(android.support.v4.app.NotificationCompat) File(java.io.File) Interceptor(okhttp3.Interceptor)

Example 33 with Request

use of com.tonyodev.fetch2.Request in project azure-sdk-for-java by Azure.

the class AuthenticationTests method canCRUDWebAppWithAuthentication.

@Test
@Ignore("Need facebook developer account")
public void canCRUDWebAppWithAuthentication() throws Exception {
    // Create with new app service plan
    WebApp webApp1 = appServiceManager.webApps().define(WEBAPP_NAME_1).withRegion(Region.US_WEST).withNewResourceGroup(RG_NAME_1).withNewWindowsPlan(PricingTier.BASIC_B1).defineAuthentication().withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK).withFacebook("appId", "appSecret").attach().create();
    Assert.assertNotNull(webApp1);
    Assert.assertEquals(Region.US_WEST, webApp1.region());
    AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId());
    Assert.assertNotNull(plan1);
    Assert.assertEquals(Region.US_WEST, plan1.region());
    Assert.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier());
    Request request = new Request.Builder().url("http://" + webApp1.defaultHostName()).get().build();
    String response = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build().newCall(request).execute().body().string();
    Assert.assertTrue(response.contains("do not have permission"));
    // Update
    webApp1.update().updateAuthentication().withAnonymousAuthentication().parent().apply();
    request = new Request.Builder().url("http://" + webApp1.defaultHostName()).get().build();
    response = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build().newCall(request).execute().body().string();
    Assert.assertFalse(response.contains("do not have permission"));
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 34 with Request

use of com.tonyodev.fetch2.Request in project azure-sdk-for-java by Azure.

the class KeyVaultCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request().url();
            Map<String, String> challengeMap = cache.getCachedChallenge(url);
            if (challengeMap != null) {
                // Get the bearer token
                String credential = getAuthenticationCredentials(challengeMap);
                Request newRequest = chain.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
                return chain.proceed(newRequest);
            } else {
                // response
                return chain.proceed(chain.request());
            }
        }
    });
    // Caches the challenge for failed request and re-send the request with
    // access token.
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            // if challenge is not cached then extract and cache it
            String authenticateHeader = response.header(WWW_AUTHENTICATE);
            Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
            // Cache the challenge
            cache.addCachedChallenge(response.request().url(), challengeMap);
            // Get the bearer token from the callback by providing the
            // challenges
            String credential = getAuthenticationCredentials(challengeMap);
            if (credential == null) {
                return null;
            }
            // be cached anywhere in our code.
            return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
        }
    });
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) Map(java.util.Map) HashMap(java.util.HashMap) HttpUrl(okhttp3.HttpUrl) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 35 with Request

use of com.tonyodev.fetch2.Request in project azure-sdk-for-java by Azure.

the class MockIntegrationTestBase method recordRequestAndResponse.

private Response recordRequestAndResponse(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();
    NetworkCallRecord networkCallRecord = new NetworkCallRecord();
    networkCallRecord.Headers = new HashMap<>();
    try {
        if (request.header("Content-Type") != null) {
            networkCallRecord.Headers.put("Content-Type", request.header("Content-Type"));
        }
        if (request.header("x-ms-version") != null) {
            networkCallRecord.Headers.put("x-ms-version", request.header("x-ms-version"));
        }
        if (request.header("User-Agent") != null) {
            networkCallRecord.Headers.put("User-Agent", request.header("User-Agent"));
        }
        networkCallRecord.Method = request.method();
        networkCallRecord.Uri = applyRegex(request.url().toString().replaceAll("\\?$", ""));
    } catch (Exception e) {
    }
    Response response = chain.proceed(chain.request());
    networkCallRecord.Response = new HashMap<>();
    try {
        networkCallRecord.Response.put("StatusCode", Integer.toString(response.code()));
        extractResponseData(networkCallRecord.Response, response);
        // remove pre-added header if this is a waiting or redirection
        if (networkCallRecord.Response.get("Body").contains("<Status>InProgress</Status>") || Integer.parseInt(networkCallRecord.Response.get("StatusCode")) == HttpStatus.SC_TEMPORARY_REDIRECT) {
        } else {
            synchronized (testRecord.networkCallRecords) {
                testRecord.networkCallRecords.add(networkCallRecord);
            }
        }
    } catch (Exception e) {
    }
    return response;
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException)

Aggregations

Request (okhttp3.Request)1601 Response (okhttp3.Response)1009 IOException (java.io.IOException)519 Test (org.junit.Test)406 OkHttpClient (okhttp3.OkHttpClient)330 RequestBody (okhttp3.RequestBody)255 Call (okhttp3.Call)239 ResponseBody (okhttp3.ResponseBody)187 HttpUrl (okhttp3.HttpUrl)139 Callback (okhttp3.Callback)109 Map (java.util.Map)85 File (java.io.File)77 InputStream (java.io.InputStream)77 JSONObject (org.json.JSONObject)76 MediaType (okhttp3.MediaType)75 Buffer (okio.Buffer)73 List (java.util.List)71 Headers (okhttp3.Headers)71 FormBody (okhttp3.FormBody)64 HashMap (java.util.HashMap)63