Example usage for com.squareup.okhttp Response message

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

Introduction

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

Prototype

String message

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

Click Source Link

Usage

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

/**
 * Download file from redirect request//w  w w . j  av a 2 s  .  c o m
 *
 * @param request for redirect
 * @return File
 * @throws RequestFailException
 */
public synchronized File downloadFile(@NonNull Request request, String filename) throws RequestFailException {
    try {
        File file = new File(mContext.getFilesDir(), TextUtils.isEmpty(filename) ? "Untitled" : filename);

        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            FilesUtils.copyFile(response.body().byteStream(), new FileOutputStream(file));
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
        return file;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

@Override
public void deleteFile(@NonNull CFile file) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }//from   ww w  .ja  v  a 2 s .c  om

    Request request = new Request.Builder().url(API_BASE_URL + "/drive/items/" + file.getId())
            .header("Authorization", String.format("Bearer %s", mAccessToken)).delete().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Log.d(TAG, "File with the id: " + file.getName() + " deleted");
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

@Override
public List<Object> search(@NonNull String keyword, CFolder folder) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }/*from  ww  w.j a v  a2 s .  co m*/

    List<Object> list = new ArrayList<>();

    Uri uri = Uri.parse(API_BASE_URL);
    String url = uri.buildUpon().appendEncodedPath("drive/items/" + folder.getId() + "/view.search")
            .appendQueryParameter("q", keyword).build().toString();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            JSONArray entries = jsonObject.getJSONArray("value");
            if (entries.length() > 0) {
                list.addAll(createFilteredItemsList(entries, folder));
            } else {
                // return null if no item found
                return null;
            }
            // pagination available
            if (jsonObject.has("@odata.nextLink")) {
                list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
            }
            return list;
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

/**
 * Get continue search items/*from w w  w .  j  a v  a2  s  . c o  m*/
 *
 * @param url for the next page of items
 * @param folder where the search is looking at
 * @return List that contains CFile and CFolder
 * @throws RequestFailException that content various error types
 */
public synchronized List<Object> searchContinue(String url, CFolder folder) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }

    List<Object> list = new ArrayList<>();

    Request request = new Request.Builder().url(url)
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = new JSONObject(response.body().string());
            JSONArray entries = jsonObject.getJSONArray("data");
            if (entries.length() > 0) {
                list.addAll(createFilteredItemsList(entries, folder));
            } else {
                // return null if no item found
                return null;
            }
            // pagination available
            if (jsonObject.has("@odata.nextLink")) {
                list.addAll(searchContinue(jsonObject.getString("@odata.nextLink"), folder));
            }
            return list;
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.OneDriveApi.java

License:Apache License

@Override
public File getThumbnail(@NonNull CFile file) throws RequestFailException {
    if (TextUtils.isEmpty(mAccessToken)) {
        throw new RequestFailException("Access token not available");
    }// w  w  w . j a va2s. c o m

    Request request = new Request.Builder()
            .url(API_BASE_URL + "/drive/items/" + file.getId() + "/thumbnails/0/medium/content")
            .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build();

    try {
        Response response = mHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            switch (response.code()) {
            case 200:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".jpg");
            case 302:
                // redirect to url
                return downloadFile(response.request(), file.getId() + ".jpg");
            }
        } else {
            throw new RequestFailException(response.message(), response.code());
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new RequestFailException(e.getMessage());
    }
    return null;
}

From source file:com.ichg.service.volley.OkHttpStack.java

License:Open Source License

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    OkHttpClient client = mClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from   ww  w . ja v a 2  s . c  om
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

License:Open Source License

private void sendRequest(BaseRequest request, @Nonnull Request.Builder builder, String requestBody,
        String method) {//from www .  j  a va2s  .co  m
    String uri = null;
    long waitTime = 0L;
    try {
        setHeaders(request, builder, request.getHeaderInformation());

        List<String> cookies = new ArrayList<String>();
        if (((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().getCookies() != null) {
            for (HttpCookie httpCookie : ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore()
                    .getCookies()) {
                cookies.add("REQUEST COOKIE: " + httpCookie.toString());
            }
        }

        Request okRequest = builder.build();
        uri = okRequest.uri().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + okRequest.method() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        request.logRequest(uri, requestBody, okRequest.method(), request.getHeaderInformation(), cookies,
                false);

        Response response = okHttpClient.newCall(okRequest).execute();
        long startTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));
        long endTime = Long.parseLong(response.header("OkHttp-Sent-Millis"));

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.code() != 203 && response.code() != 202 && response.code() != 204) {
            try {
                responseBody = response.body().bytes();
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }

        processResponse(responseBody, startTime, endTime, request, response.message(), response.code(),
                response.headers());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method + " to url " + uri + " |  error: " + ex.toString(), LogEventType.IO),
                ex);
        throw new RuntimeException(ex);
    } finally {
        if (method.equalsIgnoreCase("post") && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.jaspersoft.android.jaspermobile.webview.intercept.okhttp.OkResponseMapper.java

License:Open Source License

public WebResponse toWebViewResponse(Response response) {
    final String mimeType = response.header(CONTENT_TYPE);
    final String encoding = response.header(CONTENT_ENCODING);
    final InputStream data = extractData(response);
    final int statusCode = response.code();
    final String reasonPhrase = response.message();
    final Map<String, String> responseHeaders = extractHeaders(response);

    return new WebResponse() {
        @Override/*  w  w  w . j av a  2  s .co  m*/
        public String getMimeType() {
            return mimeType;
        }

        @Override
        public String getEncoding() {
            return encoding;
        }

        @Override
        public InputStream getData() {
            return data;
        }

        @Override
        public int getStatusCode() {
            return statusCode;
        }

        @Override
        public String getReasonPhrase() {
            return reasonPhrase;
        }

        @Override
        public Map<String, String> getResponseHeaders() {
            return responseHeaders;
        }
    };
}

From source file:com.joeyfrazee.nifi.reporting.HttpProvenanceReporter.java

License:Apache License

private void post(String json, String url) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = getHttpClient().newCall(request).execute();
    getLogger().info("{} {} {}",
            new Object[] { Integer.valueOf(response.code()), response.message(), response.body().string() });
}

From source file:com.magnet.max.android.MaxRestAuthenticator.java

License:Apache License

private void renewAppToken(final AtomicReference<String> refreshedToken) {
    // Clean up existing token
    ModuleManager.onAppLogout(MaxCore.getConfig().getClientId());

    String authHeader = AuthUtil.generateBasicAuthToken(MaxCore.getConfig().getClientId(),
            MaxCore.getConfig().getClientSecret());
    final CountDownLatch latch = new CountDownLatch(1);
    getApplicationService()/*from www.jav a  2s  .  c o m*/
            .appCheckin(Device.getCurrentDeviceId(), authHeader, new Callback<AppLoginResponse>() {
                @Override
                public void onResponse(retrofit.Response<AppLoginResponse> response) {
                    if (response.isSuccess()) {
                        Log.i(TAG, "appCheckin success : ");
                    } else {
                        handleError(response.message());
                        return;
                    }
                    AppLoginResponse appCheckinResponse = response.body();
                    refreshedToken.set(appCheckinResponse.getAccessToken());
                    ModuleManager.onAppLogin(MaxCore.getConfig().getClientId(),
                            new ApplicationToken(appCheckinResponse.getExpiresIn(),
                                    appCheckinResponse.getAccessToken(), appCheckinResponse.getTokenType(),
                                    appCheckinResponse.getScope(), appCheckinResponse.getMmxAppId()),
                            appCheckinResponse.getServerConfig());

                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable throwable) {
                    handleError(throwable.getMessage());
                    latch.countDown();
                }

                private void handleError(String errorMessage) {
                    Log.e(TAG, "appCheckin failed due to : " + errorMessage);
                    ModuleManager.onAppTokenInvalid();
                }
            }).executeInBackground();

    try {
        latch.await(REFRESH_TOKEN_TIMEOUT, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        Log.d(TAG, "refresh app token timeout");
    }
}