Example usage for com.squareup.okhttp Response request

List of usage examples for com.squareup.okhttp Response request

Introduction

In this page you can find the example usage for com.squareup.okhttp Response request.

Prototype

Request request

To view the source code for com.squareup.okhttp Response request.

Click Source Link

Usage

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

/**
 * ============Delivery============//from   w w  w  .jav a2 s  .c  om
 */
protected void deliveryAsyncResult(OkHttpClient client, Request request, HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    Util.log("Headers:\n" + request.headers().toString());

    final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback;

    //Call start
    callStart(resCallBack, request);

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            Util.log("onFailure:" + request.toString());
            callFailure(resCallBack, request, null, e);
            callFinish(resCallBack);
        }

        @Override
        public void onResponse(final Response response) {
            try {
                Object ret = null;
                final String string = response.body().string();
                final boolean haveValue = !TextUtils.isEmpty(string);

                Util.log("onResponse:Code:%d Body:%s.", response.code(), (haveValue ? string : "null"));

                if (haveValue) {
                    ret = mResolver.analysis(string, resCallBack.getClass());
                }

                callSuccess(resCallBack, ret, response.code());
            } catch (Exception e) {
                Util.log("onResponse Failure:" + response.request().toString());
                callFailure(resCallBack, response.request(), response, e);
            }
            callFinish(resCallBack);
        }
    });
}

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

protected <T> T deliveryResult(Class<T> tClass, Request request, HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    Util.log("Headers:\n" + request.headers().toString());
    if (callback == null && tClass == null)
        callback = new DefaultCallback();
    final Class<?> subClass = tClass == null ? callback.getClass() : tClass;

    callStart(callback, request);//from   w  ww.ja v  a2 s.  co  m
    Call call = mOkHttpClient.newCall(request);
    Response response = null;
    Object ret = null;
    try {
        response = call.execute();
        final String string = response.body().string();
        final boolean haveValue = !TextUtils.isEmpty(string);

        Util.log("onResponse:Code:%d Body:%s.", response.code(), (haveValue ? string : "null"));

        if (haveValue) {
            ret = mResolver.analysis(string, subClass);
        }

        callSuccess(callback, ret, response.code());
    } catch (Exception e) {
        Request req = response == null ? request : response.request();
        Util.log("onResponse Failure:" + req.toString());
        callFailure(callback, req, response, e);
    }
    callFinish(callback);
    return (T) ret;
}

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

protected void deliveryAsyncResult(final Request request, final StreamCall call,
        final HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback;

    //Call start//from ww w.j a v a 2s.c  o m
    callStart(resCallBack, request);

    mOkHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            Util.log("onFailure:" + request.toString());
            callFailure(resCallBack, request, null, e);
            callFinish(resCallBack);
        }

        @Override
        public void onResponse(final Response response) {
            OutputStream out = call.getOutputStream();
            InputStream in = null;
            byte[] buf = new byte[mBufferSize];
            try {
                Util.log("onResponse:Code:%d Stream.", response.code());

                ResponseBody body = response.body();
                bindResponseProgressCallback(request.body(), body, callback);

                in = body.byteStream();

                int size;
                while ((size = in.read(buf)) != -1) {
                    out.write(buf, 0, size);
                    out.flush();
                }
                // On success
                call.onSuccess(response.code());
            } catch (Exception e) {
                Util.log("onResponse Failure:" + response.request().toString());
                callFailure(resCallBack, response.request(), response, e);
            } finally {
                com.squareup.okhttp.internal.Util.closeQuietly(in);
                com.squareup.okhttp.internal.Util.closeQuietly(out);
            }
            callFinish(resCallBack);
        }
    });
}

From source file:net.yatomiya.nicherry.services.bbs.BBSHttpClient.java

License:Open Source License

BBSHttpClient(IEclipseContext context) {
    super();//  w  w  w .j  av  a  2s  . c  o  m

    this.context = context;

    //        setRetryOnConnectionFailure(false);
    //        setFollowRedirects(false);
    //        setFollowSslRedirects(false);

    getDispatcher().setMaxRequestsPerHost(1);

    cookieManager = context.get(PersistenceService.class).get(
            BBSHttpClient.class.getName() + "." + CookieManager.class.getName(), () -> new CookieManager());
    setCookieHandler(cookieManager);

    setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            return null;
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            if (getProxy() != null && proxyCredentials != null) {
                if (!proxyCredentials.equals(response.request().header("Proxy-Authorization"))) {
                    return response.request().newBuilder().header("Proxy-Authorization", proxyCredentials)
                            .build();
                }
            }

            return null;
        }
    });

    intervalInterceptor = new AccessIntervalInterceptor();

    interceptors().add((chain) -> interceptRequest(chain));
    interceptors().add((chain) -> interceptGetDat(chain));

    {
        PreferenceService prefs = context.get(PreferenceService.class);
        prefs.subscribe(this, NPreferences.NODE, NPreferences.NETWORK_PROXY_ENABLE,
                event -> applyProxyPreference());
        prefs.subscribe(this, NPreferences.NODE, NPreferences.NETWORK_PROXY_HOST,
                event -> applyProxyPreference());
        prefs.subscribe(this, NPreferences.NODE, NPreferences.NETWORK_PROXY_PORT,
                event -> applyProxyPreference());
        prefs.subscribe(this, NPreferences.NODE, NPreferences.NETWORK_PROXY_BASIC_USERNAME,
                event -> applyProxyPreference());
        prefs.subscribe(this, NPreferences.NODE, NPreferences.NETWORK_PROXY_BASIC_PASSWORD,
                event -> applyProxyPreference());
        prefs.subscribe(this, NPreferences.NODE, NPreferences.BBS_NETWORK_CONNECT_INTERVAL_PER_HOST,
                event -> intervalInterceptor.interval = Integer.valueOf(event.getValue()));
    }
}

From source file:net.yatomiya.nicherry.services.bbs.PostMessageHandler.java

License:Open Source License

void doOnResponse(Response response) {
    int statusCode = response.code();

    try {//from w  w w.j a v  a 2  s .  co  m
        String responseBody = StringUtils.getString(response.body().bytes(), NConstants.CHARSET_SHIFT_JIS);
        postEvent.setupWithResponse(getModel(), response.request(), response, responseBody);
    } catch (Exception e) {
        postEvent.setupConnectionError(getModel(), response.request(), e);
    }

    doFinish();
}

From source file:org.addhen.birudo.data.net.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Timber.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
            request.headers()));//from   ww  w  . j  av a 2s .co  m

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Timber.i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d,
            response.headers()));

    return response;
}

From source file:org.apache.nifi.processors.standard.util.MultiAuthenticator.java

License:Apache License

@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
    String credential = Credentials.basic(proxyUsername, proxyPassword);
    return response.request().newBuilder().header("Proxy-Authorization", credential).build();
}

From source file:org.eyeseetea.malariacare.network.ServerAPIController.java

License:Open Source License

@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
    return response.request().newBuilder().header(AUTHORIZATION_HEADER, credentials).build();
}

From source file:org.floens.chan.core.http.HttpCall.java

License:Open Source License

@Override
public void onResponse(Response response) {
    try {//from  ww  w .j  av a2s  .  co m
        if (response.isSuccessful() && response.body() != null) {
            String responseString = response.body().string();
            process(response, responseString);
            successful = true;
        } else {
            onFailure(response.request(), null);
        }
    } catch (IOException e) {
        Logger.e(TAG, "IOException processing response", e);
    } finally {
        IOUtils.closeQuietly(response.body());
    }

    AndroidUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            postUI(successful);
        }
    });
}

From source file:org.floens.chan.core.manager.ReplyManager.java

License:Open Source License

public void postPass(String token, String pin, final PassListener passListener) {
    FormEncodingBuilder formBuilder = new FormEncodingBuilder();

    formBuilder.add("act", "do_login");

    formBuilder.add("id", token);
    formBuilder.add("pin", pin);

    Request.Builder request = new Request.Builder().url(ChanUrls.getPassUrl()).post(formBuilder.build());

    makeOkHttpCall(request, new Callback() {
        @Override//  w  w w  .  j  ava2  s  .co m
        public void onFailure(Request request, IOException e) {
            final PassResponse res = new PassResponse();
            res.isError = true;
            res.message = context.getString(R.string.pass_error);
            runUI(new Runnable() {
                public void run() {
                    passListener.onResponse(res);
                }
            });
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (!response.isSuccessful()) {
                onFailure(response.request(), null);
                return;
            }
            String responseString = response.body().string();
            response.body().close();

            final PassResponse res = new PassResponse();
            if (responseString.contains("Your device is now authorized")) {
                List<String> cookies = response.headers("Set-Cookie");
                String passId = null;
                for (String cookie : cookies) {
                    try {
                        List<HttpCookie> parsedList = HttpCookie.parse(cookie);
                        for (HttpCookie parsed : parsedList) {
                            if (parsed.getName().equals("pass_id") && !parsed.getValue().equals("0")) {
                                passId = parsed.getValue();
                            }
                        }
                    } catch (IllegalArgumentException ignored) {
                    }
                }
                if (passId != null) {
                    res.passId = passId;
                    res.message = "Success! Your device is now authorized.";
                } else {
                    res.isError = true;
                    res.message = "Could not get pass id";
                }
            } else {
                res.isError = true;
                if (responseString.contains("Your Token must be exactly 10 characters")) {
                    res.message = "Incorrect token";
                } else if (responseString.contains("You have left one or more fields blank")) {
                    res.message = "You have left one or more fields blank";
                } else if (responseString.contains("Incorrect Token or PIN")) {
                    res.message = "Incorrect Token or PIN";
                } else {
                    res.unknownError = true;
                }
            }

            runUI(new Runnable() {
                public void run() {
                    passListener.onResponse(res);
                }
            });
        }
    });
}