Example usage for com.squareup.okhttp Response body

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

Introduction

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

Prototype

ResponseBody body

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

Click Source Link

Usage

From source file:com.codemodlabs.coordinate.Token.java

License:Open Source License

private void executeCallback(String url) {
    class CallbackTask extends AsyncTask {
        @Override/*from w  w w  . j a  va  2  s  . c o m*/
        protected Object doInBackground(Object[] objects) {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder().url((String) objects[0]).build();

            Response response = null;
            String body_string = "";
            try {
                response = client.newCall(request).execute();
                body_string = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Gson gson = new Gson();
            callback = gson.fromJson(body_string, Callback.class);
            return callback;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            try {
                getTokenFromServer((Callback) result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    new CallbackTask().execute(url);
}

From source file:com.codemodlabs.coordinate.Token.java

License:Open Source License

private void getTokenFromServer(Callback callback) throws IOException {

    class GetTokenTask extends AsyncTask {

        @Override/*from  w w w.ja va  2 s  .c o m*/
        protected Object doInBackground(Object[] objects) {
            try {
                final String access_code = ((Callback) objects[0]).access_code;
                String url_string = "https://login.uber.com/oauth/token";

                OkHttpClient client = new OkHttpClient();

                // Ignore invalid SSL endpoints.
                client.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });

                RequestBody formBody = new FormEncodingBuilder().add("client_secret", client_secret)
                        .add("client_id", client_id).add("grant_type", "authorization_code")
                        .add("redirect_uri", redirect_url).add("code", access_code).build();
                Request request = new Request.Builder().url(url_string).post(formBody).build();

                Response response = client.newCall(request).execute();
                String response_body = response.body().string();

                Gson gson = new Gson();
                token = gson.fromJson(response_body, Token.class);
                return token;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            Token token = (Token) result;

            Intent resultIntent = new Intent();
            resultIntent.putExtra("access_token", token.access_token);
            resultIntent.putExtra("expires_in", token.expires_in);
            resultIntent.putExtra("token_type", token.token_type);
            resultIntent.putExtra("refresh_token", token.refresh_token);
            resultIntent.putExtra("scope", token.scope);

            setResult(2, resultIntent);
            finish();
        }
    }
    new GetTokenTask().execute(callback);
}

From source file:com.coinomi.wallet.ExchangeRatesProvider.java

License:Open Source License

@Nullable
private JSONObject requestExchangeRatesJson(final URL url) {
    // Return null if no connection
    final NetworkInfo activeInfo = connManager.getActiveNetworkInfo();
    if (activeInfo == null || !activeInfo.isConnected())
        return null;

    final long start = System.currentTimeMillis();

    OkHttpClient client = NetworkUtils.getHttpClient(getContext().getApplicationContext());
    Request request = new Request.Builder().url(url).build();

    try {/*from  w w w  . j a  v a2 s  .c  om*/
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url,
                    System.currentTimeMillis() - start);
            return new JSONObject(response.body().string());
        } else {
            log.warn("Error HTTP code '{}' when fetching exchange rates from {}", response.code(), url);
        }
    } catch (IOException e) {
        log.warn("Error '{}' when fetching exchange rates from {}", e.getMessage(), url);
    } catch (JSONException e) {
        log.warn("Could not parse exchange rates JSON: {}", e.getMessage());
    }
    return null;
}

From source file:com.commonsware.android.backup.RestoreRosterFragment.java

License:Apache License

@Override
public void onResponse(Response response) throws IOException {
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ").create();

    Type listType = new TypeToken<List<BackupMetadata>>() {
    }.getType();/*from  w w w .j a va  2  s  .  c  o  m*/

    EventBus.getDefault().post(gson.fromJson(response.body().charStream(), listType));
}

From source file:com.commonsware.android.backup.RestoreService.java

License:Apache License

@Override
protected void onHandleIntent(Intent i) {
    Request request = new Request.Builder().url(i.getData().toString()).build();

    try {/*  w w w.j  a  va2 s  . c om*/
        Response response = BackupService.OKHTTP_CLIENT.newCall(request).execute();
        File toRestore = new File(getCacheDir(), "backup.zip");

        if (toRestore.exists()) {
            toRestore.delete();
        }

        BufferedSink sink = Okio.buffer(Okio.sink(toRestore));

        sink.writeAll(response.body().source());
        sink.close();

        ZipUtils.unzip(toRestore, getFilesDir(), BackupService.ZIP_PREFIX_FILES);
        ZipUtils.unzip(toRestore, BackupService.getSharedPrefsDir(this), BackupService.ZIP_PREFIX_PREFS);
        ZipUtils.unzip(toRestore, getExternalFilesDir(null), BackupService.ZIP_PREFIX_EXTERNAL);

        EventBus.getDefault().post(new RestoreCompletedEvent());
    } catch (Exception e) {
        Log.e(getClass().getSimpleName(), "Exception restoring backup", e);
        EventBus.getDefault().post(new RestoreFailedEvent());
    }
}

From source file:com.commonsware.android.okhttp.LoadThread.java

License:Apache License

@Override
public void run() {
    try {// ww  w.  java 2  s.co  m
        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);
    }
}

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call addSessionParticipantCall(String sessionId, ParticipantCreationRequest body,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = body;

    // create path and map variables
    String localVarPath = "/sessions/{session_id}/participants".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "session_id" + "\\}", apiClient.escapeString(sessionId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json" };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override/*from  www  . j  a  va2s.  c  om*/
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call createSessionCall(SessionCreationRequest body,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = body;

    // create path and map variables
    String localVarPath = "/sessions".replaceAll("\\{format\\}", "json");

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = { "application/json" };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override/*www.  ja va 2  s.  com*/
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call deleteSessionCall(String sessionId,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // create path and map variables
    String localVarPath = "/sessions/{session_id}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "session_id" + "\\}", apiClient.escapeString(sessionId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };//ww  w. j  av  a  2s .com
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}

From source file:com.coviu.sessions.api.SessionApi.java

License:Apache License

private com.squareup.okhttp.Call deleteSessionParticipantCall(String participantId,
        final ProgressResponseBody.ProgressListener progressListener,
        final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
    Object localVarPostBody = null;

    // create path and map variables
    String localVarPath = "/participants/{participant_id}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "participant_id" + "\\}", apiClient.escapeString(participantId.toString()));

    List<Pair> localVarQueryParams = new ArrayList<Pair>();

    Map<String, String> localVarHeaderParams = new HashMap<String, String>();

    Map<String, Object> localVarFormParams = new HashMap<String, Object>();

    final String[] localVarAccepts = { "application/json" };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
    if (localVarAccept != null)
        localVarHeaderParams.put("Accept", localVarAccept);

    final String[] localVarContentTypes = {

    };/*from  w ww .  j  a v a  2 s  . c o m*/
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
    localVarHeaderParams.put("Content-Type", localVarContentType);

    if (progressListener != null) {
        apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain)
                    throws IOException {
                com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new ProgressResponseBody(originalResponse.body(), progressListener)).build();
            }
        });
    }

    String[] localVarAuthNames = new String[] { "oauth2" };
    return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody,
            localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}