Example usage for com.squareup.okhttp Response code

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

Introduction

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

Prototype

int code

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

Click Source Link

Usage

From source file:com.rukiasoft.androidapps.cocinaconroll.gcm.RegistrationIntentService.java

License:Open Source License

/**
 * Persist registration to third-party servers.
 *
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.//ww w  .  j  av a2s.  c  o  m
 *
 * @param token The new token.
 */
private boolean sendRegistrationToServer(String token) {
    // this will register device for testing porposes.
    /*if (regService == null) {
    //uncomment for testing local registration for emulators
    Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(),
            new AndroidJsonFactory(), null)
            // Need setRootUrl and setGoogleClientRequestInitializer only for local testing,
            // otherwise they can be skipped
            .setRootUrl("http://10.0.2.2:8080/_ah/api/")
            .setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
                @Override
                public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
                        throws IOException {
                    abstractGoogleClientRequest.setDisableGZipContent(true);
                }
            });
    // end of optional local run code
            
    //uncomment for testing appEngine with real device. URL: http://hardy-binder-89508.appspot.com/
    //Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
    //        .setRootUrl("https://hardy-binder-89508.appspot.com/_ah/api/");
            
    regService = builder.build();
    }*/

    RegistrationResponse error = new RegistrationResponse();

    Tools mTools = new Tools();

    RegistrationClass registrationClass = new RegistrationClass(this);

    registrationClass.setGcm_regid(token);
    registrationClass.setVersion(mTools.getAppVersion(getApplication()));
    registrationClass.setEmail(mTools.getStringFromPreferences(this, Constants.PROPERTY_DEVICE_OWNER_EMAIL));
    registrationClass.setName(mTools.getStringFromPreferences(this, Constants.PROPERTY_DEVICE_OWNER_NAME));

    String urlBase = BuildConfig.RASPBERRY_IP + getResources().getString(R.string.server_url_tomcat);
    String method = getResources().getString(R.string.registration_method);

    RestTools restTools = new RestTools();
    Response response = restTools.doRestRequest(urlBase, method, mTools.getJsonString(registrationClass));

    if (response != null && response.code() == HttpURLConnection.HTTP_OK) {
        LogHelper.i(TAG, "comprobacin Registrado correctamente");
        Gson gResponse = new Gson();
        error = gResponse.fromJson(response.body().charStream(), RegistrationResponse.class);
    } else {
        LogHelper.i(TAG, "comprobacin NO registrado");
    }

    return error.getError() == 0;
}

From source file:com.secupwn.aimsicd.utils.RequestTask.java

@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 {/*from   w w  w.j  a  va2  s .  c o m*/
            @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 DBE_DOWNLOAD_REQUEST: // OCID download request from "APPLICATION" drawer title
        mTimeOut = REQUEST_TIMEOUT_MENU;
    case DBE_DOWNLOAD_REQUEST_FROM_MAP: // OCID download request from "Antenna Map Viewer"
        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();
                okHttpClient.setReadTimeout(10, TimeUnit.SECONDS); // Restore back to default
            } 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!");
                    total = 1024; // Let's set it arbitrarily to something other than "-1"
                } else {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                    publishProgress((int) (0.25 * total), (int) total); // Let's show something!
                }

                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;
}

From source file:com.shadowmaps.example.service.ShadowMapsService.java

License:Apache License

private void postUpdate(final OutgoingInfo packet) {
    new AsyncTask<Void, Void, Void>() {

        @Override/*from www. j av  a 2  s.  co  m*/
        protected Void doInBackground(Void... params) {
            try {
                String toSend = objectMapper.writeValueAsString(packet);
                RequestBody body = RequestBody.create(JSON, toSend);
                Request request = new Request.Builder().url(URL_TO_POST).post(body).build();
                Response response = client.newCall(request).execute();
                String response_str = response.body().string();
                Log.v(TAG, String.format("Received ShadowMapsUpdate: %s", response_str));
                if (response.code() == 200) {
                    Log.v("HTTP", "200!");
                    try {
                        Intent intent = new Intent();
                        long time_processed = System.currentTimeMillis();
                        ServerResponse message = objectMapper.readValue(response_str, ServerResponse.class);
                        Log.v("Server JSON", "Got Message");
                        double lon = message.getDeviceInfo().getLon();
                        double lat = message.getDeviceInfo().getLat();
                        double acc = message.getDeviceInfo().getAcc();
                        if (message.getRouteInfo() != null) {
                            double route_lon = message.getRouteInfo().getLongitude();
                            double route_lat = message.getRouteInfo().getLatitude();
                            double route_acc = message.getRouteInfo().getAccuracyHoriz();
                            intent.putExtra("clamp_lat", route_lat);
                            intent.putExtra("clamp_lon", route_lon);
                            intent.putExtra("clamp_radius", route_acc);
                            intent.putExtra("street", message.getRouteInfo().getStreetName());
                        }
                        Log.v("ShadowMaps", "Location Update received.");
                        intent.setAction("shadowmaps.location.update");
                        intent.putExtra("lat", lat);
                        intent.putExtra("lon", lon);
                        intent.putExtra("radius", acc);
                        intent.putExtra("orig_lat", packet.getDev().getLat());
                        intent.putExtra("orig_lon", packet.getDev().getLon());
                        intent.putExtra("orig_acc", packet.getDev().getAcc());

                        Log.v("ShadowMaps", String.format("Lat/Lon: %s,%s. Radius:%s", lat, lon, acc));
                        sendBroadcast(intent);
                        return null;
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.v("Exception", e.getMessage());
                    }
                } else {
                    Log.v("HTTP", "" + response.code());

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }.execute();
}

From source file:com.shahul3d.indiasatelliteweather.service.DownloaderService.java

License:Open Source License

@Background
public void downloadMap(int mapID) {
    //TODO: Check internet
    String mapType = appConstants.getMapType(mapID);
    String lastModifiedHeader = "";
    Log.d("Download requested for map type: " + mapType);
    updateDownloadStatus(mapID, 0);/*w  w w . j  av a2 s. c  o  m*/

    final String URL = appConstants.MAP_URL.get(mapType);

    try {
        Call call = httpClient.newCall(new Request.Builder().url(URL).get().build());
        Response response = call.execute();

        //TODO: These caching headers should be stored on preferences.
        String eTagHeader = response.header("ETag", "");
        lastModifiedHeader = response.header("Last-Modified", "");

        //            Log.d("eTagHeader: " + eTagHeader);
        Log.d("last modified: " + lastModifiedHeader);
        //            Log.d("\nN/W counts: " + httpClient.getCache().getNetworkCount() + "\nReq Counts: " + httpClient.getCache().getRequestCount() + "\nCache Hits: " + httpClient.getCache().getHitCount());

        if (response.code() == 200) {
            InputStream inputStream = null;
            ByteArrayOutputStream outArrrayIPStream = null;
            try {
                inputStream = response.body().byteStream();
                outArrrayIPStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int statusUpdateTrigger = 0;
                long downloaded = 0;
                long responseSize = response.body().contentLength();

                Log.d("Total size: " + responseSize);

                for (int count; (count = inputStream.read(buffer)) != -1;) {
                    outArrrayIPStream.write(buffer, 0, count);
                    downloaded += count;
                    statusUpdateTrigger++;
                    //                        Log.d(String.format("%d / %d", downloaded, responseSize));

                    //Update download status
                    if (statusUpdateTrigger > appConstants.STATUS_UPDATE_THRESHOLD) {
                        //                            Thread.sleep(3000);
                        statusUpdateTrigger = 0;
                        Long downloadedPercent = downloaded * appConstants.MAX_DOWNLOAD_PROGRESS / responseSize;
                        Log.d("downloaded percent: " + downloadedPercent);
                        updateDownloadStatus(mapID, downloadedPercent.intValue());
                    }
                }

                byte[] responseImage = outArrrayIPStream.toByteArray();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inMutable = true;
                Bitmap bmp = BitmapFactory.decodeByteArray(responseImage, 0, responseImage.length, options);

                bmp = removeMapBorders(mapType, bmp);

                //Save downloaded image for offline use.
                saveDownloadedMap(mapType, bmp);
                updateDownloadStatus(mapID, 100);
            } catch (IOException ignore) {
                trackException("MAP download & parser error", ignore);
                broadcastDownloadStatus(mapID, false);
                //Error on fetching & organizing the binary data.
                return;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outArrrayIPStream != null) {
                    outArrrayIPStream.close();
                }
            }
        } else {
            trackException("res code other than 200: " + response.code(), null);
            Log.d("res code other than 200 " + response.code());
            return;
        }
    } catch (IOException e) {
        trackException("MAP download connection error", e);
        broadcastDownloadStatus(mapID, false);
        return;
    }

    preferenceUtil.updateLastModifiedTime(preference_General, mapType, lastModifiedHeader);
    broadcastDownloadStatus(mapID, true);
}

From source file:com.shopify.buy.data.MockResponseGenerator.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    File file = new File(context.getExternalFilesDir(null), "MobileBuy.json");

    if (file == null) {
        return chain.proceed(chain.request());
    }/*ww  w  . ja v a 2s  . co  m*/

    if (!file.exists()) {
        file.createNewFile();
    }

    String jsonKey = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement());

    Request request = chain.request();
    Response response = chain.proceed(request);
    String bodyString = response.body().string();

    JsonObject jsonValue = new JsonObject();
    jsonValue.addProperty(MockResponder.KEY_BODY, bodyString);
    jsonValue.addProperty(MockResponder.KEY_CODE, response.code());
    jsonValue.addProperty(MockResponder.KEY_MESSAGE, response.message());

    FileOutputStream fOut = new FileOutputStream(file, true);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(fOut));
    writer.println("\"" + jsonKey + "\":" + jsonValue.toString() + ",");

    if (!isPartialAddressTestAdded.getAndSet(true)) {
        writer.println(TEST_WITH_PARTIAL_ADDRESS_RESPONSE);
    }

    writer.flush();
    fOut.flush();
    writer.close();
    fOut.close();

    MediaType contentType = response.body().contentType();
    return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
}

From source file:com.sonaive.v2ex.sync.api.Api.java

License:Open Source License

public Bundle sync(HttpMethod httpMethod) {
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = null;//from   w w w .j  av  a 2 s  .  c  o  m

    if (httpMethod == HttpMethod.GET) {
        request = new Request.Builder().url(mUrl).build();
    } else {
        String json = mArguments.getString(ARG_API_PARAMS);
        HashMap params = new Gson().fromJson(json, HashMap.class);
        FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : ((HashMap<String, String>) params).entrySet()) {
            formBodyBuilder.add(entry.getKey(), entry.getValue());
        }
        RequestBody formBody = formBodyBuilder.build();
        request = new Request.Builder().url(mUrl).post(formBody).build();
    }

    try {
        Response response = okHttpClient.newCall(request).execute();
        if (response != null && response.code() == 200) {
            LOGD(TAG, "Request: " + mUrl + ", server returned HTTP_OK, so fetching was successful.");
            mArguments.putString(Api.ARG_RESULT, response.body().string());
            return mArguments;
        } else if (response != null && response.code() == 403) {
            LOGW(TAG, "Request: " + mUrl + ", Server returned 403, fetching was failed.");
        } else {
            LOGW(TAG, "Request: " + mUrl + ", Fetching was failed. Unknown reason");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sonaive.v2ex.sync.api.UserIdentityApi.java

License:Open Source License

public void verifyUserIdentity(final String accountName,
        final WeakReference<LoginHelper.Callbacks> callbacksRef) {

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(mUrl + "?username=" + accountName).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        @Override/*from w  ww .  ja va  2 s  .  c o  m*/
        public void onFailure(Request request, IOException e) {
            JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            result.addProperty("err_msg", "IOException");
            if (callbacksRef != null) {
                callbacksRef.get().onIdentityCheckedFailed(result);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            JsonObject result = new JsonObject();
            if (response.code() == 200) {
                String responseBody = response.body().string();
                try {
                    JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
                    String status = jsonObject.get("status").getAsString();
                    if (status != null && status.equals("found")) {
                        result.addProperty("result", "ok");
                        LOGD(TAG, "userInfo: " + responseBody);
                        AccountUtils.setActiveAccount(mContext, accountName);
                        V2exDataHandler dataHandler = new V2exDataHandler(mContext);

                        Bundle data = new Bundle();
                        data.putString(Api.ARG_RESULT, responseBody);
                        data.putString(V2exDataHandler.ARG_DATA_KEY, V2exDataHandler.DATA_KEY_MEMBERS);
                        dataHandler.applyData(new Bundle[] { data });

                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedSuccess(result);
                        }
                    } else if (status != null && status.equals("notfound")) {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_user_not_found));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    } else {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_unknown_error));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    }
                } catch (JsonSyntaxException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "JsonSyntaxException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                } catch (UnsupportedOperationException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "UnsupportedOperationException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                }
            } else if (response.code() == 403) {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", "403 Forbidden");
                if (callbacksRef != null) {
                    callbacksRef.get().onIdentityCheckedFailed(result);
                }
            }
            LOGD(TAG, "responseCode: " + response.code() + ", result: " + result.get("result") + ", err_msg: "
                    + result.get("err_msg"));
        }
    });
}

From source file:com.sonaive.v2ex.util.LoginHelper.java

License:Open Source License

/** After spent hours digging, I give up */
private void signIn(String onceCode) {

    Map<String, String> params = new HashMap<>();
    params.put("next", "/");
    params.put("u", mAccountName);
    params.put("p", mPassword);
    params.put("once", onceCode);

    RequestBody postBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), params.toString());

    Request request = new Request.Builder().header("Origin", "http://www.v2ex.com")
            .header("Referer", "http://www.v2ex.com/signin").header("X-Requested-With", "com.android.browser")
            .header("Cache-Control", "max-age=0")
            .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
            .header("Accept-Language", "zh-CN, en-US")
            .header("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7")
            .url(Api.API_URLS.get(Api.API_SIGNIN)).post(postBody).build();

    try {//from   www  .  jav  a  2 s.  c  om

        okHttpClient.setFollowRedirects(false);
        Response response = okHttpClient.newCall(request).execute();

        final JsonObject result = new JsonObject();
        Pattern errorPattern = Pattern.compile("<div class=\"problem\">(.*)</div>");
        Matcher errorMatcher = errorPattern.matcher(response.body().string());
        final String errorContent;

        if (response.code() == 302) {// temporary moved, 302 found, disallow redirects.
            LOGD(TAG, "sign in success!");
            getUserInfo();
            return;
        } else if (errorMatcher.find()) {
            errorContent = errorMatcher.group(1).replaceAll("<[^>]+>", "");
        } else {
            errorContent = "Unknown error";
        }

        if (errorContent != null) {
            result.addProperty("result", "fail");
            result.addProperty("err_msg", errorContent);
            LOGD(TAG, "sign in error, err_msg = " + errorContent);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sonaive.v2ex.util.LoginHelper.java

License:Open Source License

/** Get signed in account info(node collections, account name), need cookie */
private void getUserInfo() {
    Request request = new Request.Builder().url(Api.API_URLS.get(Api.API_MY_NODES)).build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override//from  w  w  w.  j ava  2  s.  c  om
        public void onFailure(Request request, IOException e) {
            JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            result.addProperty("err_msg", mAppContext.getString(R.string.err_get_node_collections_failed));
            if (mCallbacksRef != null) {
                mCallbacksRef.get().onNodeCollectionFetchedFailed(result);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {

            JsonObject result = new JsonObject();

            if (response.code() == 200) {
                Pattern userPattern = Pattern.compile("<a href=\"/member/([^\"]+)\" class=\"top\">");
                Matcher userMatcher = userPattern.matcher(response.body().string());
                if (userMatcher.find()) {

                    String accountName = userMatcher.group(1);
                    Pattern collectionPattern = Pattern.compile("</a>&nbsp; <a href=\"/go/([^\"]+)\">");
                    Matcher collectionMatcher = collectionPattern.matcher(response.body().string());
                    List<String> collections = new ArrayList<>();
                    if (collectionMatcher.find()) {
                        collections.add(collectionMatcher.group(1));
                        while (collectionMatcher.find()) {
                            collections.add(collectionMatcher.group(1));
                        }
                    }
                    // TODO add the user node collections into database
                    LOGD(TAG, "Get user: " + accountName + " node collections: " + collections.toString());
                    result.addProperty("result", "ok");
                    if (mCallbacksRef != null) {
                        mCallbacksRef.get().onNodeCollectionFetchedSuccess(result);
                    }
                } else {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", mAppContext.getString(R.string.err_get_my_nodes_failed));
                    if (mCallbacksRef != null) {
                        mCallbacksRef.get().onNodeCollectionFetchedFailed(result);
                    }
                }
            } else if (response.code() == 403) {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", "403 Forbidden");
                if (mCallbacksRef != null) {
                    mCallbacksRef.get().onIdentityCheckedFailed(result);
                }

            } else {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", mAppContext.getString(R.string.err_unknown_error));
                if (mCallbacksRef != null) {
                    mCallbacksRef.get().onIdentityCheckedFailed(result);
                }
            }

            LOGD(TAG, "responseCode: " + response.code() + ", result: " + result.get("result") + ", err_msg: "
                    + result.get("err_msg"));
        }
    });
}

From source file:com.squareup.picasso252.OkHttpDownloader.java

License:Apache License

@Override
public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;//ww  w.jav a  2s . c o  m
    if (networkPolicy != 0) {
        if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
            cacheControl = CacheControl.FORCE_CACHE;
        } else {
            CacheControl.Builder builder = new CacheControl.Builder();
            if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
                builder.noCache();
            }
            if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
                builder.noStore();
            }
            cacheControl = builder.build();
        }
    }

    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }

    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
        response.body().close();
        throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
}